Pandas: Elementwise multiplication of two dataframes

我怕爱的太早我们不能终老 提交于 2019-11-28 07:34:07
In [161]: pd.DataFrame(df.values*df2.values, columns=df.columns, index=df.index)
Out[161]: 
   col1  col2  col3
1    10   200  3000
2    10   200  3000
3    10   200  3000
4    10   200  3000
5    10   200  3000

A simpler way to do this is just to multiply the dataframe whose colnames you want to keep with the values (i.e. numpy array) of the other, like so:

In [63]: df * df2.values
Out[63]: 
   col1  col2  col3
1    10   200  3000
2    10   200  3000
3    10   200  3000
4    10   200  3000
5    10   200  3000

This way you do not have to write all that new dataframe boilerplate.

This works for me:

mul = df.mul(df3.c, axis=0)

Or, when you want to subtract (divide) instead:

sub = df.sub(df3.c, axis=0)
div = df.div(df3.c, axis=0)

Works also with a nan in df (e.g. if you apply this to the df: df.iloc[0]['col2'] = np.nan)

To utilize Pandas broadcasting properties, you can use multiply.

df.multiply(df3['col1'], axis=0)

Another way is create list of columns and join them:

cols = [pd.DataFrame(df[col] * df3.col1, columns=[col]) for col in df]
mul = cols[0].join(cols[1:])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!