我想取两个数据帧并将它们相乘以制作第三个数据帧。
说我有
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
如何在一行中完成此操作?
答案 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