给定以下数据框:
import pandas as pd
p1 = {'name': 'willy', 'age': 11, 'interest': "Lego"}
p2 = {'name': 'willy', 'age': 11, 'interest': "games"}
p3 = {'name': 'zoe', 'age': 9, 'interest': "cars"}
df = pd.DataFrame([p1, p2, p3])
df
age interest name
0 11 Lego willy
1 11 games willy
2 9 cars zoe
我想知道每个人的兴趣总和,并让每个人只在列表中显示一次。我执行以下操作:
Interests = df[['age', 'name', 'interest']].groupby(['age' , 'name']).count()
Interests.reset_index(inplace=True)
Interests.sort('interest', ascending=False, inplace=True)
Interests
age name interest
1 11 willy 2
0 9 zoe 1
这可行,但我感觉我做错了。现在我使用“兴趣”列来显示我的总和值,这没关系,但就像我说的那样,我希望有一种更好的方法来做到这一点。
我在 Pandas 中看到了很多关于计数/求和的问题,但对我来说,省略“重复项”的部分是关键。