akrylic
akrylic

Reputation: 53

Multiply columns of a pandas Dataframe by different scalars

I have a pandas DataFrame df with columns col_1, col_2, ..., col_n.

I want to multiply each column of the pandas Dataframe by a different scalar based on the column. For example, multiply each of the elements in col_1 by n_1, each of the elements in col_2 by n_2 etc... What is the neatest way to do this?

Currently my solution involves creating the dictionary {col_1: n_1, col_2: n_2, ...}. I then create a dataframe out of this with constant columns. This dataframe has the same columns as df and the values in each column are looked up from the dictionary.

I then multiply df and df_2.

I am using Python 2.7.10 and pandas 0.24.2.

Upvotes: 0

Views: 2058

Answers (2)

mozway
mozway

Reputation: 260845

You can use a dictionary and mul:

df = pd.DataFrame({'col1': [1,2,3], 'col2': [4,5,6]})
df.mul({'col1': 2, 'col2': 10})

input:

   col1  col2
0     1     4
1     2     5
2     3     6

output:

   col1  col2
0     2    40
1     4    50
2     6    60

Upvotes: 2

Meti
Meti

Reputation: 2056

If you have no problem with hardcoded scalers, there is a pythonic way to do so

df = pd.DataFrame({'angles': [0, 3, 4],

                   'degrees': [360, 180, 360]},

                  index=['circle', 'triangle', 'rectangle'])
df * [1, 2]

output

    angles  degrees
circle  0   720
triangle    3   360
rectangle   4   720

Upvotes: 3

Related Questions