pandas groupby分别制作两列列表 [英] Pandas groupby make two columns lists separately
问题描述
我目前有一个包含三列的DataFrame.为了方便起见,我们将它们称为fruit
,sport
和weather
.
I currently have a DataFrame that has three columns. Let's call them fruit
, sport
, and weather
for the sake of convenience.
我要做的是按fruit
列对DataFrame进行分组,并将sport
和weather
的相应值放入列表中,以便为它们提供相应的sport
和weather
列表每个唯一的fruit
.
What I want to do is to group the DataFrame by the fruit
column and make the corresponding values for sport
and weather
into lists so that we'll have corresponding sport
and weather
lists for each unique fruit
.
例如:
# Original DataFrame
fruit sport weather
0 apple baseball sunny
1 banana swimming cloudy
2 apple basketball windy
3 orange football sunny
4 banana hockey windy
# Desired DataFrame
fruit sport weather
0 apple [baseball, basketball] [sunny, windy]
1 banana [swimming, hockey] [cloudy, windy]
2 orange [football] [sunny]
将一个列值分组到一个列表中是相对简单的,但是我对于如何使用两个列值有点困惑.我该怎么办?预先感谢.
Grouping one of the column values into a list is relatively straightforward, but I'm a bit stuck as to how to do that with two. How might I go about that? Thanks in advance.
推荐答案
您可以groupby
并使用list
构造函数进行聚合:
You can groupby
and aggregate witht the list
constructor:
df.groupby('fruit', as_index=False).agg(list)
fruit sport weather
0 apple [baseball, basketball] [sunny, windy]
1 banana [swimming, hockey] [cloudy, windy]
2 orange [football] [sunny]
这篇关于 pandas groupby分别制作两列列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!