How To Apply For Loop To Append Rows Based On Multiple Calculation?
I have a very complex situation to append the rows with one agg. function of sum of population based on different columns. Find below: Please make sure I have multiple rows in all
Solution 1:
d = { 'year': [2019,2020,2021,2020,2019,2021],
'age': [10,20,30,10,20,30],
'con': ['UK','UK','UK','US','US','US'],
'population': [1,2,300,400,1000,2000]}
df = pd.DataFrame(data=d)
df2 = df.copy()
criteria = [df2['age'].between(0, 10),
df2['age'].between(11, 20),
df2['age'].between(21, 30)]
values = ['child', 'teen', 'work']
df2['con'] = df2['con']+'_'+np.select(criteria, values, 0)
df2['population'] = df.groupby(['con', 'age']).sum()\
.groupby(level=0).cumsum()\
.reset_index()['population']
final = pd.concat([df, df2])
Post a Comment for "How To Apply For Loop To Append Rows Based On Multiple Calculation?"