Suppose I have this table;
A B C
2 1 4
1 8 2
...
I try to divide each row with column C value, then I get;
A B C
0.5 0.25 4
0.5 4 2
How can I do it in pandas dataframe
Use the built in div
function and pass param axis=0
:
In [123]:
df[['A','B']] = df[['A','B']].div(df['C'],axis=0)
df
Out[123]:
A B C
0 0.5 0.25 4
1 0.5 4.00 2
You can simply do df[col] = df[col] / df[col2]
where col
and col2
could be 'A'
and 'C'
, for example.
The code below will divide A and B by C in turn. You can ignore the first part, that's just be setting the DataFrame up.
import pandas as pd
from io import StringIO
s = '''A B C
2 1 4
1 8 2'''
df = pd.read_csv(StringIO(s), sep='\s+')
print(df)
# A B C
# 0 2 1 4
# 1 1 8 2
df['A'] = df['A'] / df['C'] # or df['A'] /= df['C']
df['B'] = df['B'] / df['C'] # or df['B'] /= df['C']
print(df)
# A B C
# 0 0.5 0.25 4
# 1 0.5 4.00 2
To make this easier (if you have multiple columns) you could have a list of column names ['A', 'B']
and then iterate over it
for x in ['A', 'B']:
df[x] /= df['C']
for x in ['A', 'B']: df[x] /= df['C']
Does the 'C' shoulbe in the last column? Because loop stops when df('C')/df('C')
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.