根据列将两个pandas DataFrames相乘 [英] Multiply two pandas DataFrames based on column

查看:2688
本文介绍了根据列将两个pandas DataFrames相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个DataFrame,如何将它们按列相乘以产生一个带有结果的DataFrame.例如...

If I have two DataFrames how do I multiply them together by column to produce a DataFrame with the result. For example...

 df1 = pd.DataFrame(np.random.randint(10, size=(5, 4)), columns=['A', 'B', 'C', 'D'])

    A  B  C  D
 0  6  9  3  8
 1  1  7  9  9
 2  6  2  0  8
 3  3  6  8  4
 4  6  0  4  8

 df2 = pd.DataFrame(np.random.randint(10, size=(5, 4)), columns=['A', 'B', 'C', 'D'])


    A  B  C  D
 0  9  8  5  3
 1  9  5  6  7
 2  6  9  6  3
 3  7  6  2  5
 4  1  5  2  7

结果就是这样.....

The result would be this.....

    A  B  C  D
 0 54 72 15 24
 1  9 35 54 63

等.

推荐答案

[CW;只是将其从未回答的问题列表中删除.]

[CW; just to take this off the unanswered questions list..]

我认为您想要df1 * df2.例如:

>>> df1 = pd.DataFrame(np.random.randint(10, size=(5, 4)), columns=['A', 'B', 'C', 'D'])
>>> df2 = pd.DataFrame(np.random.randint(10, size=(5, 4)), columns=['A', 'B', 'C', 'D'])
>>> df1
   A  B  C  D
0  0  6  5  7
1  8  6  4  0
2  6  2  4  3
3  8  8  7  6
4  8  7  9  0

[5 rows x 4 columns]
>>> df2
   A  B  C  D
0  0  0  3  0
1  8  5  6  5
2  7  4  9  7
3  8  4  4  1
4  2  5  6  4

[5 rows x 4 columns]
>>> df1 * df2
    A   B   C   D
0   0   0  15   0
1  64  30  24   0
2  42   8  36  21
3  64  32  28   6
4  16  35  54   0

[5 rows x 4 columns]

这篇关于根据列将两个pandas DataFrames相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆