使用python对数据帧中的项进行分组
我有一个python数据框,其中包含以下字段:使用python对数据帧中的项进行分组,python,pandas,dataframe,group-by,Python,Pandas,Dataframe,Group By,我有一个python数据框,其中包含以下字段: id date cost A 2017-01-17 19 A 2017-01-17 22 A 2017-03-29 19 A 2017-03-29 10 B 2017-03-16 25 是否可以在两列id和date上对数据框进行分组,然后根据分组得到最大和最小成本 id date
id date cost
A 2017-01-17 19
A 2017-01-17 22
A 2017-03-29 19
A 2017-03-29 10
B 2017-03-16 25
是否可以在两列id
和date
上对数据框进行分组,然后根据分组得到最大和最小成本
id date max(cost) min(cost)
A 2017-01-17 22 19
A 2017-03-29 19 10
B 2017-03-16 25 25
使用
groupby
+agg
:
df.groupby(['id', 'date']).cost\
.agg([('cost(max)', 'max'), ('cost(min)', 'min')]).reset_index()
id date cost(max) cost(min)
0 A 2017-01-17 22 19
1 A 2017-03-29 19 10
2 B 2017-03-16 25 25
使用
groupby
+agg
:
df.groupby(['id', 'date']).cost\
.agg([('cost(max)', 'max'), ('cost(min)', 'min')]).reset_index()
id date cost(max) cost(min)
0 A 2017-01-17 22 19
1 A 2017-03-29 19 10
2 B 2017-03-16 25 25
或使用apply
df.groupby(['id', 'date'],as_index=False).cost.apply(lambda x : pd.Series([min(x),max(x)],index=['min(cost)','max(cost)']))
Out[1021]:
min(cost) max(cost)
id date
A 2017-01-17 19 22
2017-03-29 10 19
B 2017-03-16 25 25
或使用apply
df.groupby(['id', 'date'],as_index=False).cost.apply(lambda x : pd.Series([min(x),max(x)],index=['min(cost)','max(cost)']))
Out[1021]:
min(cost) max(cost)
id date
A 2017-01-17 19 22
2017-03-29 10 19
B 2017-03-16 25 25
这么快LOL:-)这么快LOL:-)