【问题标题】:Row-wise lookup from other data frame从其他数据帧逐行查找
【发布时间】:2018-12-10 21:37:01
【问题描述】:

我有两个数据框,我想根据某些条件进行组合。这是第一个数据帧,每一行代表一个观察(因此 ID 出现多次):

df1

  ID  Count  Publication
0  A     10         1990
1  B     15         1990
2  A     17         1990
3  B     19         1991
4  A     13         1991

这是第二个数据框。在这里,每个 ID 只显示一次,但随着时间的推移(这里是 1990 年到 1993 年)。

df2

  ID  1990  1991  1992  1993
0  A   1.1   1.2   1.3   1.4
1  B   2.3   2.4   2.4   2.6
2  C   3.4   3.5   3.6   3.7
3  D   4.5   4.6   4.7   4.8

我的目标是向 df1 添加一个结果列,其中我将 df1["Count"] 列中的值与 df2 中的相应值(ID-Year 对)相乘,例如第一行:“1990”中的“ID”A 是 1.1 乘以“Count”10 = 11。

results

  ID  Count  Publication  Results
0  A     10         1990     11.0
1  B     15         1990     34.5
2  A     17         1990     18.7
3  B     19         1991     45.6
4  A     13         1991     15.6

到目前为止,我已经尝试了多个使用 pandas .apply() 函数的选项,但没有成功。我也尝试过 .merge() 根据 ID 从 df2 到 df1 的列,但之后我仍然无法进行计算(我希望这可以简化问题)。

问题:是否有一种简单有效的方法可以逐行遍历 df1 并从 df2 中“挑选”相应的值进行计算?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用lookup

    df2.set_index('ID').lookup(df1.ID,df1.Publication.astype(str))
    Out[189]: array([1.1, 2.3, 1.1, 2.4, 1.2])
    
    df1['Results']=df2.set_index('ID').lookup(df1.ID,df1.Publication.astype(str))*(df1.Count)
    df1
    Out[194]: 
      ID  Count  Publication  Results
    0  A     10         1990     11.0
    1  B     15         1990     34.5
    2  A     17         1990     18.7
    3  B     19         1991     45.6
    4  A     13         1991     15.6
    

    【讨论】:

    • 完美运行,谢谢!我知道一定有一个简单的方法:)
    【解决方案2】:

    我真的不知道它的效率如何,但你可以这样做:

    df1 = df1.set_index(['ID', 'Publication'])
    df2 = df2.set_index('ID').stack()
    df2.index.rename(['ID', 'Publication'], inplace=True)
    df1['df2_value'] = df2
    df1['result'] = df1['Count'] * df1['df2_value']
    

    【讨论】:

      猜你喜欢
      • 2015-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      • 2011-05-16
      • 2020-12-17
      相关资源
      最近更新 更多