acb
acb

Reputation: 625

Pandas DataFrame multiplying columns and creating new columns

I have some data that has 11 columns. I need to multiply columns 1-10 by column 11 and then create 10 new columns with those results. To do this I am using pandas DataFrame.

Now I understand how to do this for each column individually with a code like this

df['newcolumn1'] = df['column1']*df['column11']
df['newcolumn2'] = df['column2']*df['column11']
df['newcolumn3'] = df['column3']*df['column11']

I'm assuming I can set up a function and a loop to iterate through the columns and create the new columns. Is there anyway I can do this by referencing the column index number instead of the column names.

Upvotes: 1

Views: 1623

Answers (1)

miradulo
miradulo

Reputation: 29690

Instead of multiplying individually or explicitly looping, you could use multiply to generate a DataFrame of your new columns, then pd.concat to join things together. Doing so by column number as you would like to may look like

pd.concat([df, 
           (df.iloc[:, :10].multiply(df.iloc[:, -1], axis='rows')
                           .add_prefix('new_'))], 
           axis=1)

Minimal example

>>> df
   column1  column2  column3  column4
0        0        1        2        3
1        4        5        6        7
2        8        9       10       11
3       12       13       14       15

>>> pd.concat([df, 
                (df.iloc[:, :3].multiply(df.iloc[:, -1], axis='rows')
                               .add_prefix('new_')], axis=1))], 
                axis=1)

   column1  column2  column3  column4  new_column1  new_column2  new_column3
0        0        1        2        3            0            3            6
1        4        5        6        7           28           35           42
2        8        9       10       11           88           99          110
3       12       13       14       15          180          195          210

Upvotes: 3

Related Questions