【问题标题】:Update a column in a data frame with the index of another column in another data frame in pandas python用pandas python中另一个数据框中的另一列的索引更新数据框中的一列
【发布时间】:2015-11-28 09:22:27
【问题描述】:

我在 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])

但是我正在处理一个大数据集,因此需要花费太多时间,我正在寻找一个更快的选项来执行此操作。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    我建议使用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
    

    【讨论】:

      猜你喜欢
      • 2021-06-11
      • 1970-01-01
      • 2020-10-27
      • 2017-04-13
      • 2019-07-26
      • 2022-08-10
      • 1970-01-01
      • 2019-11-23
      • 2021-04-28
      相关资源
      最近更新 更多