3

I have two DataFrames, as follows :

df1 = 


 name1 name2  name3   ....    nameXXX 
  5.1   1.2    1.1    ...      223.2
  3.22  1.34   1.5    ...      213.2
  4.3   1.32   1.23   ...      523.2
  5.2   1.1    1.543  ...      223.2

df2=

name1     0.2
name2     0.1
name3     0.43
...       ...
nameXXX   0.21

What I need :

df3=

 name1       name2         name3     ...         nameXXX 
5.1 * 0.2   1.2 * 0.1    1.1 * 0.43  ...      223.2 *  0.21
3.22* 0.2   1.34* 0.1    1.5 * 0.43  ...      213.2 * 0.21
4.3 * 0.2   1.32* 0.1    1.2 * 0.43  ...      523.2 * 0.21
5.2 * 0.2   1.1 * 0.1    1.54* 0.43  ...      223.2 *  0.21
  • the names are the column headers

  • Basically I want to multiply each column of df1 by the number present in df2 that is in the same row of the column header of df1

I saw the following questions but I couldn't find the solution to my problem :

1) How to select rows from a DataFrame based on column values?

2)Pandas: pairwise multiplication of columns based on column name

3) Multiply columns of a dataframe by getting the column names from a list

4)pandas: Select dataframe columns based on another dataframe's columns

3 Answers 3

2

If name column is your index, you can just do

df1.mul(df2.iloc[:,0], axis='columns')

If it's is a normal column, you can set it as an index:

df1.mul(df2.set_index(0).iloc[:,0], axis='columns')

Output:

   name1  name2    name3  nameXXX
0  1.020  0.120  0.47300   46.872
1  0.644  0.134  0.64500   44.772
2  0.860  0.132  0.52890  109.872
3  1.040  0.110  0.66349   46.872
Sign up to request clarification or add additional context in comments.

Comments

1

Let us do

df1=df1.mul(df2,axis=1)

Comments

0

I think what you need is to update the column, essentially if you have the same number of columns as rows in your other df, you can try:

cols = df1.columns for i in cols: df1[i] = df1[i] * df2.loc[i].values

Typing from phone sorry for formatting

Comments

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.