gpt4 book ai didi

python - 基于不同的 DataFrame 在 pandas DataFrame 中追加列

转载 作者:行者123 更新时间:2023-12-01 05:21:13 24 4
gpt4 key购买 nike

我有这两个数据框:

df1

A B
0 8 x
1 3 y
2 1 x
3 2 z
4 7 y

and

df2
A B
0 x hey
1 y there
2 z sir

我正在尝试根据 df2['B'] 附加 df1['B'] ,以便我想要的输出为:

df3

A B
0 8 hey
1 3 there
2 1 hey
3 2 sir
4 7 there

是否有内置方法可以进行这种转换?我正在尝试类似的东西,但我无法让它正常运行:

for x in df1['B']:
if df2['A'] == x:
df1['B'].append.df2['B']

最佳答案

我相信您会想要一个简单的合并:

In [10]: df1.merge(df2, left_on='B', right_on='A')
Out[10]:
A_x B_x A_y B_y
0 8 x x hey
1 1 x x hey
2 3 y y there
3 7 y y there
4 2 z z sir

如果您想保持索引的顺序:

In [11]: df1.reset_index().merge(df2, left_on='B', right_on='A').set_index('index').sort_index()
Out[11]:
A_x B_x A_y B_y
index
0 8 x x hey
1 3 y y there
2 1 x x hey
3 2 z z sir
4 7 y y there

关于python - 基于不同的 DataFrame 在 pandas DataFrame 中追加列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22315245/

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