我有以下数据帧:
Sport | AgeGroup |
---|---|
棒球 | 0秒|
足球 | 0秒|
棒球 | 30秒 |
棒球 | 0秒|
足球 | 0秒|
足球 | 0秒|
足球 | 30秒 |
另一个解决方案,使用.agg()
:
print(
df.groupby(["Sport", "AgeGroup"], as_index=False)
.size()
.agg(list, axis=1)
.tolist()
)
打印:
[['Baseball', '20s', 2], ['Baseball', '30s', 1], ['Football', '20s', 3], ['Football', '30s', 1]]
如果您想要一个数组(便于索引(,您可以重置索引,并在分组后使用to_numpy()
sport_age_count.reset_index().to_numpy()
array([['Baseball', '20s', 2],
['Baseball', '30s', 1],
['Football', '20s', 3],
['Football', '30s', 1]], dtype=object)
但如果你想要一个列表列表,你可以使用numpy的tolist()
sport_age_count.reset_index().to_numpy().tolist()
[['Baseball', '20s', 2],
['Baseball', '30s', 1],
['Football', '20s', 3],
['Football', '30s', 1]]