如果将两个其他数据帧相乘以产生它,如何一次性设置pandas数据框中的所有值?

时间:2017-10-18 22:02:40

标签: python pandas dataframe vectorization

我想取两个数据帧并将它们相乘以制作第三个数据帧。

说我有

            HI   BYE  HE  HER   
Date                                                   
2011-01-10  2     2    2   2 
2011-01-13  2     2    2   2    
2011-01-13  2     2    2   2   
2011-01-26  2     2    2   2

            BRO  CHICK DUDE MAN   
Date                                                   
2011-01-10  2     2    2     2 
2011-01-13  2     2    2     2    
2011-01-13  2     2    2     2   
2011-01-26  2     2    2     2

我想要,

            MY  NAME  IS    SLIM_SHADY   
Date                                                   
2011-01-10  4     4    4     4 
2011-01-13  4     4    4     4    
2011-01-13  4     4    4     4   
2011-01-26  4     4    4     4

如何在一行中完成此操作?

1 个答案:

答案 0 :(得分:3)

使用np.array转换为.values并执行逐元素乘法。

df = pd.DataFrame(df1.values * df2.values,
         index=df1.index, columns="MY NAME IS SLIM_SHADY".split())
print(df)
            MY  NAME  IS  SLIM_SHADY
Date                                
2011-01-10   4     4   4           4
2011-01-13   4     4   4           4
2011-01-13   4     4   4           4
2011-01-26   4     4   4           4

另一种方法是重命名索引,然后调用df.mul

df2.columns = df1.columns  # could also add df2.index = df1.index for security
df = df1.mul(df2)
df.columns="MY NAME IS SLIM_SHADY".split()

print(df)
            MY  NAME  IS  SLIM_SHADY
Date                                
2011-01-10   4     4   4           4
2011-01-13   4     4   4           4
2011-01-13   4     4   4           4
2011-01-26   4     4   4           4