Python 在Pandas中使用Groupby后如何计算组中的项目数
我的数据框中有多个列,其中我使用了两列“客户id”和“行程id”。我使用了groupby函数Python 在Pandas中使用Groupby后如何计算组中的项目数,python,pandas,pandas-groupby,Python,Pandas,Pandas Groupby,我的数据框中有多个列,其中我使用了两列“客户id”和“行程id”。我使用了groupby函数data.groupby(['customer\u id','trip\u id')每个客户都有多个行程。我想计算每个客户的出行次数,但当我使用聚合函数和group by时,所有行中都得到了1。我应该如何进行? 我想要这种格式的东西 Example : Customer_id , Trip_Id, Count CustID1 ,trip1, 3 trip 2 trip
data.groupby(['customer\u id','trip\u id')
每个客户都有多个行程。我想计算每个客户的出行次数,但当我使用聚合函数和group by时,所有行中都得到了1。我应该如何进行?
我想要这种格式的东西
Example :
Customer_id , Trip_Id, Count
CustID1 ,trip1, 3
trip 2
trip 3
CustID2 ,Trip450, 2
Trip23
您可以使用内置nunique按客户分组并计算独特行程的数量:
data.groupby('Customer_id').agg(Count=('Trip_id', 'nunique'))
您可以使用
data.groupby('customer\u id','trip\u id').count()
例如:
df1 = pd.DataFrame(columns=["c1","c1a","c1b"], data = [[1,2,3],[1,5,6],[2,8,9]])
print(df1)
# | c1 | c1a | c1b |
# |----|-----|-----|
# | x | 2 | 3 |
# | z | 5 | 6 |
# | z | 8 | 9 |
df2 = df1.groupby("c1").count()
print(df2)
# | | c1a | c1b |
# |----|-----|-----|
# | x | 1 | 1 |
# | z | 2 | 2 |
那也行!但是,如果出于某种原因,您为一位客户两次拥有相同的trip_id,那么它将失败,因为它计算的是出现的次数,而不是唯一trip id的数量,只需确保在使用thisSure时删除重复项即可!你能考虑接受这个答案吗?或者你想让我在答案中改进什么?