Home > front end >  Pandas Dataframe multiply with a column of another dataframe
Pandas Dataframe multiply with a column of another dataframe

Time:12-22

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,:].

CodePudding user response:

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]]

CodePudding user response:

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
  • Related