在熊猫DF

时间:2019-04-17 19:09:56

标签: python-3.x pandas dataframe

给出df2 DF,其中

df2[car_colname]
             car_30    car_90  ...
2005-02-21  0.117660  0.004845 ...
2005-02-22  0.145713  0.000901 ...
2005-02-23  0.074074  0.002139 ...
2005-02-24  0.076934 -0.004596 ...
2005-02-25  0.085200 -0.016227 ...
2005-04-08  0.097728 -0.005937 ...
2005-04-11  0.222366  0.007553 ...

df2[sd_colname]
              std_30    std_90 ...
2005-02-21  0.052266  0.004150 ...
2005-02-22  0.052266  0.004150 ...
2005-02-23  0.052266  0.004150 ...
2005-02-24  0.052266  0.004150 ...
2005-02-25  0.052266  0.004150 ...
2005-04-08  0.061682  0.006731 ...
2005-04-11  0.061682  0.006731 ...

我想按行df2[car_colname]除以df2[sd_colname],以便第一行的结果来自:0.117660 / 0.052266 = 2.251176673171850.004845 / 0.004150 = 1.16746987951807,依此类推...

2005-02-21      2.25117667317185    1.16746987951807   ...
2005-02-22      2.78791183561015    0.21710843373494   ...
2005-02-23      1.41725022002832    0.515421686746988  ...
2005-02-24      1.4719703057437    -1.10746987951807   ...
2005-02-25      1.6301228331994    -3.91012048192771   ...
2005-04-08      1.58438442333258   -0.882038330114396  ...
2005-04-11      3.60503874712234    1.12212152726192   ...

我尝试df2[car_colname] / df2[sd_colname]df2[car_colname].div(df2[sd_colname])无济于事。

2 个答案:

答案 0 :(得分:2)

您可能需要将columns更改为两个dfs

df1.columns=df1.columns.str.split('_').str[-1]
df2.columns=df2.columns.str.split('_').str[-1]
df1.div(df2)
Out[786]: 
                  30        90
2005-02-21  2.251177  1.167470
2005-02-22  2.787912  0.217108
2005-02-23  1.417250  0.515422
2005-02-24  1.471970 -1.107470
2005-02-25  1.630123 -3.910120
2005-04-08  1.584384 -0.882038
2005-04-11  3.605039  1.122122

答案 1 :(得分:0)

只需替换列名称,

df1.div(df2.rename(columns = (dict(zip(df2.columns, df1.columns)))))


            car_30      car_90
2005-02-21  2.251177    1.167470
2005-02-22  2.787912    0.217108
2005-02-23  1.417250    0.515422
2005-02-24  1.471970    -1.107470
2005-02-25  1.630123    -3.910120
2005-04-08  1.584384    -0.882038
2005-04-11  3.605039    1.122122