熊猫-用多索引除以形状不规则的df

时间:2019-07-24 19:54:57

标签: python pandas

我有一些更大的表,但要说明:

import pandas as pd

df1 = pd.DataFrame(columns=['Thing1','Thing2',2017,2018,2019])
df1 = df1.append({'Thing1':'A','Thing2':5,2017:10,2018:5,2019:9}, ignore_index=True)
df1 = df1.append({'Thing1':'A','Thing2':7,2017:6,2018:13,2019:19}, ignore_index=True)
df1 = df1.append({'Thing1':'B','Thing2':2,2017:20,2018:40,2019:44}, ignore_index=True)
df1 = df1.append({'Thing1':'C','Thing2':8,2017:33,2018:17,2019:12}, ignore_index=True)
df1 = df1.append({'Thing1':'C','Thing2':4,2017:63,2018:34,2019:45}, ignore_index=True)

df1.set_index(['Thing1','Thing2'], inplace=True)

df2 = pd.DataFrame(columns=['Thing1',2017,2018,2019])
df2 = df2.append({'Thing1':'A',2017:45,2018:60,2019:100}, ignore_index=True)
df2 = df2.append({'Thing1':'B',2017:20,2018:50,2019:25}, ignore_index=True)
df2 = df2.append({'Thing1':'C',2017:88,2018:77,2019:99}, ignore_index=True)

df2.set_index('Thing1', inplace=True)


print(df1)
              2017 2018 2019
Thing1 Thing2               
A      5        10    5    9
       7         6   13   19
B      2        20   40   44
C      8        33   17   12
       4        63   34   45

print(df2)
       2017 2018 2019
Thing1               
A        45   60  100
B        20   50   25
C        88   77   99

df2包含来自另一个数据源的一些求和值。我想取df1,并除以df2中的相应数字。因此,对于最左上角的条目:(A,5)的值10除以45,得出0.2222。这是我要制作的最终作品:

                2017    2018    2019
Thing1 Thing2               
A      5        .2222   .0833   .09
       7        .1333   .2167   .19
B      2        1.0     .8      1.76
C      8        .375    .2201   .1212
       4        .7159   .4416   .4545

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

user3483203提供的答案。只需在此处发布以供他人参考。

df3 = df1/df2
print(df3)

                   2017       2018      2019
Thing1 Thing2                               
A      5       0.222222  0.0833333      0.09
       7       0.133333   0.216667      0.19
B      2              1        0.8      1.76
C      8          0.375   0.220779  0.121212
       4       0.715909   0.441558  0.454545