将数据帧与来自其他数据帧的值相乘 [英] Multiply dataframe with values from other dataframe

查看:39
本文介绍了将数据帧与来自其他数据帧的值相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据框

df1 = pd.DataFrame([[1,2],[3,4],[5,6],[7,8]], index = ['a','b','c', 'a'], columns = ['d','e'])
   d  e
a  1  2
b  3  4
c  5  6
a  7  8


df2 = pd.DataFrame([['a', 10],['b',20],['c',30],['f',40]])


   0   1
0  a  10
1  b  20
2  c  30
3  f  40

我希望我的最终数据帧将 df1 的行乘以与 df2 中的值对应的因子(例如,b 为 20)

i want my final dataframe to multiply rows of df1 to multiply by a factor corresponding to value in df2 (for eg. 20 for b)

所以我的输出应该像

     d    e
a   10   20
b   60   80
c  150  180
a   70   80

请提供一个解决方案,假设 df1 的长度为数百行.我只能想到通过 df1.index 循环.

Kindly provide a solution assuming df1 to be hundreds of rows in length. I could only think of looping through df1.index.

推荐答案

使用 set_indexreindexdf2df1 对齐 然后 mul

Use set_index and reindex to align df2 with df1 and then mul

In [1150]: df1.mul(df2.set_index(0).reindex(df1.index)[1], axis=0)
Out[1150]:
     d    e
a   10   20
b   60   80
c  150  180
a   70   80

这篇关于将数据帧与来自其他数据帧的值相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆