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 name
s 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
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
Let us do
df1=df1.mul(df2,axis=1)
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
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.