OptimusPrime
OptimusPrime

Reputation: 619

How do I multiply certain columns by a constant?

I been trying to work on this problem for the past 1 hour but with little to no success and it is a mess.

I have a df

 Age   Bronx   Manhatten  Brooklyn   Queens  
 0      10     11         13         12
 1      8      7          9          9
 2      5      8          7          6 
 3      3      2          3          4
 4      8      6          8          7
 5      10     12         13         14
 6      11     13         12         10
 7      7      8          6          8

How do I multiply all the columns (Bronx, Manhatten, Brooklyn, Queens) for the

age 0 by 0.05
age 1 by 0.02
age 2,3,4, by 0.2

and then for all the other columns drop it.

Upvotes: 0

Views: 43

Answers (2)

Pinyi Wang
Pinyi Wang

Reputation: 862

There are a lot of ways to do this:

def multiply_age(age):
    if age == 0:
        age *= 0.05
    elif age == 1:
        age *= 0.02
    elif age in {2, 3, 4}:
        age *= 0.2
    return age

df['Age'].apply(multiply_age)

df['Age'].apply(multiply_age) will return a series of age. You can then make it a dataframe by doing pd.DataFrame(df['Age'].apply(multiply_age)).

You can also try this:

def multiply_age(row):
    age = row['Age']
    if age == 0:
        age *= 0.05
    elif age == 1:
        age *= 0.02
    elif age in {2, 3, 4}:
        age *= 0.2
    row['Age'] = age
    return row

df.apply(lambda row: multiply_age(row), axis=1)['Age']

Upvotes: 1

BENY
BENY

Reputation: 323276

Using mul with your own dict to map with age

age=pd.Series({0:0.5,1:0.2,2:0.2,3:0.2,4:0.2})
df.set_index('Age').mul(age,axis=0).fillna(df.set_index('Age')).reset_index()
Out[116]: 
   index  Bronx  Manhatten  Brooklyn  Queens
0      0    5.0        5.5       6.5     6.0
1      1    1.6        1.4       1.8     1.8
2      2    1.0        1.6       1.4     1.2
3      3    0.6        0.4       0.6     0.8
4      4    1.6        1.2       1.6     1.4
5      5   10.0       12.0      13.0    14.0
6      6   11.0       13.0      12.0    10.0
7      7    7.0        8.0       6.0     8.0

Upvotes: 2

Related Questions