![](/img/trans.png)
[英]pandas: groupby and aggregate without losing the column which was grouped
[英]pandas dataframe groupby without losing the column which was grouped
在我发布的上一篇文章中,我在根据某些条件删除/求和行时遇到问题,有人帮助纠正了这样的代码。
这是我的代码:
import pandas as pd
df=pd.DataFrame({
'cars':['Kia rio','Bmw','Mercedes','Ford','Kia','Mercedes Benz'],
'rent':[1,1,2,1,4,2],
'sale':[2,4,1,1,5,1],
'id':[2000,1000,3000,4000,2000,3000]
})
print(df)
df1 = df.drop_duplicates().groupby(['id'], sort=False, as_index=False).sum()
print(df1)
但是当我运行 groupby 方法时,它会丢弃car columns 。 谁可以帮我这个事?
我得到了这个 output:
id rent sale
0 2000 5 7
1 1000 1 4
2 3000 4 2
3 4000 1 1
预期 output:
cars rent sale id
Kia 5 7 2000
Bmw 1 4 1000
Mercedes 2 1 3000
Ford 1 1 4000
您需要聚合列以将其保留在输出中(或by
参数传递给id
),因此为避免丢失cars
列,使用聚合 function last
作为每组cars
的最后一个值,也指定另外 2 列的聚合sum
:
df1 = df.drop_duplicates().groupby('id',sort=False,as_index=False).agg(cars=('cars','last'),
rent=('rent', 'sum'),
sale=('sale', 'sum'))
print(df1)
id cars rent sale
0 2000 Kia 5 7
1 1000 Bmw 1 4
2 3000 Mercedes Benz 4 2
3 4000 Ford 1 1
如果可能,按第一个空格split
carnames 并按id
和cars
聚合:
df['cars'] = df['cars'].str.split().str[0]
df1 = df.drop_duplicates().groupby(['id','cars'], sort=False, as_index=False).sum()
print(df1)
id cars rent sale
0 2000 Kia 5 7
1 1000 Bmw 1 4
2 3000 Mercedes 2 1
3 4000 Ford 1 1
我相信它正在发生,因为cars
是非数字的,默认情况下在 DataFrame 总和上会跳过它。 Sum 有一个可选参数numeric_onlybool
表示:
numeric_onlybool, default None
Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.
资料来源: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sum.html
这个问题也有一些关于对字符串部分进行分组的好信息: Pandas groupby: How to get a union of strings
import pandas as pd
df = pd.DataFrame({
'cars':['Kia rio', 'Bmw', 'Mercedes', 'Ford', 'Kia', 'Mercedes Benz'],
'rent':[1, 1, 2, 1, 4, 2],
'sale':[2, 4, 1, 1, 5, 1],
'id': [2000, 1000, 3000, 4000, 2000, 3000]
})
print(df)
df1 = df.drop_duplicates().groupby(['id', 'cars'], sort=False, as_index=False).sum()
print(df1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.