我在 pandas python 中有两个数据框:
df1:
Fruit Origin
0 Apple Spain
1 Apple France
2 Apple Italy
3 Banana Germany
4 Banana Portugal
5 Grapes France
6 Grapes Spain
df2:
Fruit
0 Apple
1 Banana
2 Grapes
并且我想通过 df2 中每个水果的索引修改 df1 中的 Fruit 列,我正在查找的结果应如下所示:
df1:
Fruit Origin
0 0 Spain
1 0 France
2 0 Italy
3 1 Germany
4 1 Portugal
5 2 France
6 2 Spain
我尝试过的有效方法是:
df1['Fruit'] = df1.Fruit.apply(lambda x: df2.index[df2.Fruit == x])
但是我正在处理大数据集,因此需要花费太多时间,我正在寻找更快的选项来执行此操作。
最佳答案
我建议使用join
。首先,我们要将 df2
的索引设置为 Fruits
列:
df2 = df2.reset_index().set_index('Fruit')
所以
index
Fruit
Apple 0
Banana 1
Grapes 2
现在我们只写:
>>> df1.join(df2, on='Fruit')
Fruit Origin index
0 Apple Spain 0
1 Apple France 0
2 Apple Italy 0
3 Banana Germany 1
4 Banana Portugal 1
5 Grapes France 2
6 Grapes Spain 2
关于python - 使用 pandas python 中另一个数据框中另一列的索引更新数据框中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33966608/