df1=pd.DataFrame(np.random.randn(6,3),index=list("ABCDEF"),columns=list("XYZ"))
df2=pd.DataFrame(np.random.randn(6,1),index=list("ABCDEF"))
我想将 df1 的每一列与 df2 相乘,并按索引标签进行匹配。这意味着:
df1["X"]*df2
df1["Y"]*df2
df1["Z"]*df2
输出将包含 df1 的索引和列。
我该怎么做?尝试了多种方法,还是不行...
最佳答案
使用mul
函数和按 Series
(列)按位置选择多个 DataFrame
iloc
:
print(df1.mul(df2.iloc[:,0], axis=0))
X Y Z
A -0.577748 0.299258 -0.021782
B -0.952604 0.024046 -0.276979
C 0.175287 2.507922 0.597935
D -0.002698 0.043514 -0.012256
E -1.598639 0.635508 1.532068
F 0.196783 -0.234017 -0.111166
详细信息:
print(df2.iloc[:, 0])
A -2.875274
B 1.881634
C 1.369197
D 1.358094
E -0.024610
F 0.443865
Name: 0, dtype: float64
关于python - pandas 数据帧按列相乘,索引匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47412502/