我有很多列的数据框,2是分类的,其余是数字的:
df = [type1 , type2 , type3 , val1, val2, val3
a b q 1 2 3
a c w 3 5 2
b c t 2 9 0
a b p 4 6 7
a c m 2 1 8]
我想基于将根据groupby(["type1","type2"])
分组行中的最大值创建的操作应用合并:
df = [type1 , type2 ,type3, val1, val2, val3
a b q 2 6 7
a c w 4 5 8
b c t 2 9 0
说明:val3
第一行是7,因为这是时的最大值type1 = a, type2 = b
。
同样,val3
第二行是8,因为这是时的最大值type1 = a, type2 = c
。
如果需要通过max
以下方式汇总所有列:
df = df.groupby(["type1","type2"]).max()
print (df)
type3 val1 val2 val3
type1 type2
a b q 4 6 7
c w 3 5 8
b c t 2 9 0
如果需要一些列聚集不同,您可以创建字典,聚合函数的列名,然后设置一些列的其它集合functuions,像type3
使用first
和val1
使用last
:
d = dict.fromkeys(df.columns.difference(['type1','type2']), 'max')
d['type3'] = 'first'
d['val1'] = 'last'
df = df.groupby(["type1","type2"], as_index=False, sort=False).agg(d)
print (df)
type1 type2 type3 val1 val2 val3
0 a b q 4 6 7
1 a c w 2 5 8
2 b c t 2 9 0
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句