python pandas dataframe 乘以匹配索引或行名称的列

标签 python pandas dataframe numpy multiplication

我有两个数据框,

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/

相关文章:

python - 在python pandas中选择最接近某个时间的时间

python - Pandas:索引距已知标签一定位置的元素的惯用方法?

r - 创建基于多个变量的人口普查表

python - 时间序列 Pandas 的滚动平均值

python - Pandas 获取月底的数据?

python - 将用户输入限制为字母

python - 使用 %s 运算符在 Python 中创建 MySQL 数据库

python - PIL海报化-修复绿色像素

Python Pandas 将列表列表的一列扩展为两个新列

python - 在python中增加财务季度