Reputation: 300
I am trying to divide my data frame with one of its columns:
Here is my data frame:
A | B | C |
---|---|---|
1 | 10 | 10 |
2 | 20 | 30 |
3 | 15 | 33 |
Now, I want to divide columns "b" and "c" by column "a", my desired output be like:
A | B | C |
---|---|---|
1 | 10 | 10 |
2 | 10 | 15 |
3 | 5 | 11 |
df/df['a']
Upvotes: 1
Views: 422
Reputation: 862591
Use DataFrame.div
:
df[['B','C']] = df[['B','C']].div(df['A'], axis=0)
print (df)
A B C
0 1 10.0 10.0
1 2 10.0 15.0
2 3 5.0 11.0
If need divide all columns without A
:
cols = df.columns.difference(['A'])
df[cols] = df[cols].div(df['A'], axis=0)
Upvotes: 2
Reputation: 24049
try this:
d = {
'A': [1,2,3],
'B': [10,20,15],
'C': [10,30,33]
}
df = pd.DataFrame(d)
df['B'] = df['B']/df['A']
df['C'] = df['C']/df['A']
print(df)
Output:
A B C
0 1 10.0 10.0
1 2 10.0 15.0
2 3 5.0 11.0
Upvotes: 2