gpt4 book ai didi

python - 根据索引合并两个数据帧(一个从数据透视表创建的 df)

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:11 25 4
gpt4 key购买 nike

我有两个数据框:

DF1:

Dept  Produce  
Acct
111 Fruit
222 Vegetable

DF2:

Acct Spent LastIn  
111 50 Monday
222 75 Tuesday

我希望我的新数据框 DF3 看起来像这样:

DF3:

Acct Produce Spent LastIn  
111 Fruit 50 Monday
222 Vegetable 75 Tuesday

我一直在尝试使用:pd.merge(DF1,DF2, on='Acct'),但收到一个以以下结尾的冗长错误:

KeyError: 'Acct'

我相信这是因为 DF1 是转换后的数据透视表,而 python 认为 DEPT 是实际索引。因此,我尝试使用 .drop 从 DF1 中删除“Acct”行,但不能,因为我收到此错误:

ValueError: labels ['Acct'] not contained in axis.

如何达到我想要的最终状态 DF3?

最佳答案

IIUC:

示例 DF:

In [57]: d1
Out[57]:
Dept Produce
Acct
111 Fruit
222 Vegetable

DF的索引:

In [60]: d1.index
Out[60]: Int64Index([111, 222], dtype='int64', name='Acct')

列:

In [61]: d1.columns
Out[61]: Index(['Produce'], dtype='object', name='Dept')

DF2:

In [58]: d2
Out[58]:
Acct Spent LastIn
0 111 50 Monday
1 222 75 Tuesday

解决方案:

In [59]: d2.merge(d1, left_on='Acct', right_index=True)
Out[59]:
Acct Spent LastIn Produce
0 111 50 Monday Fruit
1 222 75 Tuesday Vegetable

关于python - 根据索引合并两个数据帧(一个从数据透视表创建的 df),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47004905/

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