1

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

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Unfortunately I get "KeyError: 1"
Like I said, it's assuming your column names are 0,1,2 Just replace 1 with the column name from df2 you want to use
My mistake. '1' instead of 1 solved this error. But now I get a Dataframe with twice as many rows than it should and every element is = NaN
0

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

3 Comments

This approach won't work for dataframes of different shapes eg. 500x3 and 500x100 matrices, right?
But based on what you asked, you wanted to multiply a single column with another dataframe, in that case it doesn't matter.
The error I get ist "ValueError: operands could not be broadcast together with shapes (531,) (531,128)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.