使用python中另一个数据帧中另一列的索引更新数据帧中的一列
我在python中有两个数据帧: df1: df2: 我想通过df2中每个果的索引修改df1中的果列,我要查找的结果应该如下所示: df1: 我尝试的有效方法是:使用python中另一个数据帧中另一列的索引更新数据帧中的一列,python,pandas,dataframe,Python,Pandas,Dataframe,我在python中有两个数据帧: df1: df2: 我想通过df2中每个果的索引修改df1中的果列,我要查找的结果应该如下所示: df1: 我尝试的有效方法是: df1['Fruit'] = df1.Fruit.apply(lambda x: df2.index[df2.Fruit == x]) 然而,我正在处理一个大数据集,因此需要花费太多时间,我正在寻找一个更快的选项来完成这项工作。我建议使用join。首先,我们要将df2的索引设置为Fruits列: df2 = df2.reset_in
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
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