数据框如下所示:
d = {'ID': [1, 2,3],'V':['F','G','H'],'AAA':[0,1,1],'AA':[0,2,2],'A':[0,3,3],'BBB':[0,4,4]}
df2 = pd.DataFrame(data=d)
字典看起来像这样:
dct ={1:{'F':[2,3,5],'G':[3,5,6],'H':[6,7,8]},
2:{'F':[1,3,5],'G':[8,5,6],'H':[9,7,8]},
3:{'F':[5,3,5],'G':[4,5,6],'H':[10,7,8]}
}
基于“ ID”和“ V”的值,我可以从字典中访问列表,即dct [2] ['G']。如何对此应用合并?
简而言之,我想将特定列表作为一行附加到数据框。
预期结果应如下所示:
op_d = {'ID': [1, 2,3],'V':['F','G','H'],'AAA':[0,1,1],'AA':[0,2,2],'A':[0,3,3],'BBB':[0,4,4],'Q1':[2,8,10],'Q2':[3,5,7],'Q3':[5,6,8]}
output_df = pd.DataFrame(data=op_d )
使用df.lookup
从字典创建一个数据帧后dct
和隐蔽的数据帧,然后assign
:
m = pd.DataFrame(dct).T
s = df2.set_index('ID')['V']
output = df2.assign(**pd.DataFrame(m.lookup(s.index,s).tolist(),columns=['Q1','Q2','Q3']))
print(output)
ID V AAA AA A BBB Q1 Q2 Q3
0 1 F 0 0 0 0 2 3 5
1 2 G 1 2 3 4 8 5 6
2 3 H 1 2 3 4 10 7 8
对于动态重命名,请使用:
df2.assign(**pd.DataFrame(m.lookup(s.index,s).tolist()).rename(columns=lambda x:f"Q{x+1}"))
ID V AAA AA A BBB Q1 Q2 Q3
0 1 F 0 0 0 0 2 3 5
1 2 G 1 2 3 4 8 5 6
2 3 H 1 2 3 4 10 7 8
要么:
df2.assign(**pd.DataFrame(m.lookup(s.index,s).tolist()).add_prefix('Q'))
ID V AAA AA A BBB Q0 Q1 Q2
0 1 F 0 0 0 0 2 3 5
1 2 G 1 2 3 4 8 5 6
2 3 H 1 2 3 4 10 7 8
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句