简体   繁体   中英

Pandas Dataframe multiply with a column of another dataframe

Is there a way to multiply each element of a row of a dataframe by an element of the same row from a particular column of another dataframe.

For example, such that:

df1:

1 2 3
2 2 2
3 2 1

and df2:

x 1 b
z 2 c
x 4 a

results in

1  2  3
4  4  4
12 8  4

So basically such that df1[i,:] * df2[i,j] = df3[i,:] .

Here you go. I have created a variable that allows you to select that which column of the second dataframe you want to multiply with the numbers in the first dataframe.

arr1 = np.array(df1) # df1 to array

which_df2col_to_multiply = 0  # select col from df2
arr2 = np.array(df2)[:, which_df2col_to_multiply ] # selected col to array

print(np.transpose(arr2*arr1))  # result

This is the output:

[[1 2 3]
[4 4 4]
[12 8 4]]

Multiply the first df by the column of the second df

Assuming your column names are 0,1,2

df1.mul(df2[1],0)

Output

    0  1  2
0   1  2  3
1   4  4  4
2  12  8  4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM