我有两个数据框,
df1:
hash a b c
ABC 1 2 3
def 5 3 4
Xyz 3 2 -1
df2:
hash v
Xyz 3
def 5
我想做
df:
hash a b c
ABC 1 2 3 (= as is, because no matching 'ABC' in df2)
def 25 15 20 (= 5*5 3*5 4*5)
Xyz 9 6 -3 (= 3*3 2*3 -1*3)
如上所述,
我想创建一个数据帧,其中根据匹配的索引(或第一个列名称)将 df1 和 df2 相乘。 由于 df2 只有一列 (v),因此除了第一列(索引)之外的 df1 的所有列都会受到影响。
有没有什么简洁的Pythonic和Panda的方法来实现它?
df1.set_index(['hash']).mul(df2.set_index(['hash']))
或类似的东西似乎不起作用..
最佳答案
一种方法:
df1 = df1.set_index("hash")
df2 = df2.set_index("hash")["v"]
res = df1.mul(df2, axis=0).combine_first(df1)
print(res)
输出
a b c
hash
ABC 1.0 2.0 3.0
Xyz 9.0 6.0 -3.0
def 25.0 15.0 20.0
关于python pandas dataframe 乘以匹配索引或行名称的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73006362/