Tricks about Pandas 1
Contents
75. Tricks about Pandas 1#
75.1. Adding New Column from Groupby Results#
import pandas as pd
Create a dataframe
df = pd.DataFrame( {'city':['London','London','Berlin','Berlin'], 'rent': [1000, 1400, 800, 1000]} )
df
city | rent | |
---|---|---|
0 | London | 1000 |
1 | London | 1400 |
2 | Berlin | 800 |
3 | Berlin | 1000 |
df['total'] = df.groupby('city').transform('sum')
df
city | rent | total | |
---|---|---|---|
0 | London | 1000 | 2400 |
1 | London | 1400 | 2400 |
2 | Berlin | 800 | 1800 |
3 | Berlin | 1000 | 1800 |
df['percent'] = df['rent']/df['total']
df
city | rent | total | percent | |
---|---|---|---|---|
0 | London | 1000 | 2400 | 0.416667 |
1 | London | 1400 | 2400 | 0.583333 |
2 | Berlin | 800 | 1800 | 0.444444 |
3 | Berlin | 1000 | 1800 | 0.555556 |