使用DataFrame.melt
+ Series.map
:
df1=pd.DataFrame(dict1)
df1_melt=df1.melt(var_name='Name',value_name='ID')
df1_melt['value']=df1_melt.Name.map(dict2)
#df1_melt=df1_melt.set_index('ID') #If you want ID like index
print(df1_melt)
输出
Name ID value
0 A 619 600
1 A 588 600
2 B 772 680
3 B 880 680
4 C 033 300
5 C 944 300
6 D 077 100
7 D 854 100
请注意,字典1(dict1)中C和D的值必须读为字符串,因为它们以0开头
dict1 =
{
"A" :[619,588],"B" : [772,880],"C" : ['033','944'],"D" : ['077','854']
}
,
如果将第一个字典重新排列为更可行的格式,则问题将变得更加直接。
id_mapper = {x: key for key,value in dict1.items() for x in value}
df = pd.DataFrame(index = [
"619","588","772","880","033","944","077","854",])
df['Name'] = df.index.map(id_mapper)
df['Value'] = df['Name'].map(dict2)
>>> df
ID Name Value
0 619 A 600
1 588 A 600
2 772 B 680
3 880 B 680
4 033 C 300
5 944 C 300
6 077 D 100
7 854 D 100
为清楚起见,id_mapper看起来像这样:
{'619': 'A','588': 'A','772': 'B',...}
,
使用列表推导和构造函数。
pd.DataFrame([
dict(ID=el,Name=k,Value=dict2.get(k))
for k,v in dict1.items()
for el in v
])
ID Name Value
0 619 A 600
1 588 A 600
2 772 B 680
3 880 B 680
4 33 C 300
5 944 C 300
6 77 D 100
7 854 D 100
,
假设dict1
中的所有值都是唯一的:
d = {v: k for k in dict1 for v in dict1[k]}
df = pd.DataFrame({'ID': list(d.keys()),'Name': list(d.values())})
>>> df.assign(Value=df['Name'].map(dict2))
ID Name Value
0 619 A 600
1 588 A 600
2 772 B 680
3 880 B 680
4 033 C 300
5 944 C 300
6 077 D 100
7 854 D 100
或者:
d = {v: k for k in dict1 for v in dict1[k]}
df = pd.DataFrame({
'ID': list(d.keys()),'Name': list(d.values()),'Value': [dict2[val] for val in d.values()]})
,
toolz.dicttoolz.merge
from toolz.dicttoolz import merge
d1 = merge(map(dict.fromkeys,dict1.values(),dict1))
s = pd.Series(d1).rename_axis('ID')
pd.concat({'Name': s,'Value': s.map(dict2)},axis=1).reset_index()
ID Name Value
0 619 A 600
1 588 A 600
2 772 B 680
3 880 B 680
4 033 C 300
5 944 C 300
6 077 D 100
7 854 D 100
本文链接:https://www.f2er.com/3163876.html