gpt4 book ai didi

Python合并数据框和列表字典的字典

转载 作者:行者123 更新时间:2023-12-02 09:20:39 26 4
gpt4 key购买 nike

数据框如下所示:

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

关于Python合并数据框和列表字典的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59773550/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com