Say I have the following DataFrame:
data = pd.DataFrame({'id' : ['1','2','3','4','5'], 'group' : ['1','1','2','1','2'],
'state' : ['True','False','False','True','True'], 'value' : [11,12,5,8,3]})
I would like to create a new DataFrame, keeping 3 columns: groups ('1'
or '2'
), and averaging over the columns 'state'
and 'value'
, hence the DataFrame would be:
grouped_averaged = pd.DataFrame({'group' : ['1','2'], 'average_state' : [0.66,0.5], 'value' : [7,3]})
You just need groupby
:
data['state'] = data['state'].eq('True')
data.drop('id',axis=1).groupby('group', as_index=False).mean()
Output:
group state value
0 1 0.666667 10.333333
1 2 0.500000 4.000000
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加