乘大小不同的熊猫数据框

时间:2020-04-06 12:40:36

标签: python pandas dataframe data-manipulation

我有2个pandas DataFrames。

第一个包含有关美国上市公司的公司年度报告的数据。换句话说,每个观察(行)都包含一年中一家公司的数据。

第二个DataFrame具有有关年平均通胀水平的数据。

我必须将第一个df中的所有值乘以第二个df中相应年份的通货膨胀水平。我该怎么办?

Example DataFrames

df1:

index    year    firm    assets    ppe    other_variable
  0      2000     1        50       2           5
  1      2001     1        60       3           5
  2      2000     2        30       5          10
  3      2001     2        45       5           8
  4      2002     2        50      10           8
...

df2:

year    cpi
2000    1.000
2001    1.010
2002    1.022
...

1 个答案:

答案 0 :(得分:1)

如果没有创建缺少值,则可以将所有列都乘以DataFrame.iloc而不先由year映射值,因此如有必要,请在1中将其替换为fillna并乘以DataFrame.mul

y = df1['year'].map(df2.set_index('year')['cpi']).fillna(1)
df1.iloc[:, 1:] = df1.iloc[:, 1:].mul(y, axis=0)
print (df1)
   year   firm  assets    ppe  other_variable
0  2000  1.000   50.00   2.00           5.000
1  2001  1.010   60.60   3.03           5.050
2  2000  2.000   30.00   5.00          10.000
3  2001  2.020   45.45   5.05           8.080
4  2002  2.044   51.10  10.22           8.176

另一种方法是将列cpi添加到DataFrame.join的第一个DataFrame中,然后将DataFrame.pop乘以提取列:

df = df1.set_index('year').join(df2.set_index('year'))
df = df.mul(df.pop('cpi'), axis=0).reset_index()
print (df)
   year   firm  assets    ppe  other_variable
0  2000  1.000   50.00   2.00           5.000
1  2000  2.000   30.00   5.00          10.000
2  2001  1.010   60.60   3.03           5.050
3  2001  2.020   45.45   5.05           8.080
4  2002  2.044   51.10  10.22           8.176