Multiply dataframe with values from other dataframe

回眸只為那壹抹淺笑 提交于 2021-02-08 11:21:29

问题


I have two dataframes

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

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)

so my output should look like

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

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


回答1:


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



回答2:


Create a mapping and call df.apply:

In [1128]: mapping = dict(df2.values)

In [1129]: df1.apply(lambda x: x * mapping[x.name], 1)
Out[1129]: 
     d    e
a   10   20
b   60   80
c  150  180
a   70   80



回答3:


IIUC:

In [55]: df1 * pd.DataFrame(np.tile(df2[[1]],2), columns=df1.columns, index=df2[0])
Out[55]:
     d    e
a   10   20
a   70   80
b   60   80
c  150  180

Helper DF:

In [57]: pd.DataFrame(np.tile(df2[[1]],2), columns=df1.columns, index=df2[0])
Out[57]:
    d   e
0
a  10  10
b  20  20
c  30  30



回答4:


This is straight forward. You just make sure they have a common axis, then you can combine them:

put the lookup column into the index

df2.set_index(0, inplace=True)

    1
0   
a   10
b   20
c   30

Now you can put that column into df1 very easily:

df1['multiplying_factor'] = df2[1]

Now you just want to multiply two columns:

df1['final_value'] = df1.e*df1.multiplying_factor

Now df1 looks like:

    d   e   multiplying_factor  final_value
a   1   2   10                  20
b   3   4   20                  80
c   5   6   30                  180
a   7   8   10                  80


来源:https://stackoverflow.com/questions/45801885/multiply-dataframe-with-values-from-other-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!