pandas groupby分别制作两列列表 [英] Pandas groupby make two columns lists separately

查看:104
本文介绍了 pandas groupby分别制作两列列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个包含三列的DataFrame.为了方便起见,我们将它们称为fruitsportweather.

I currently have a DataFrame that has three columns. Let's call them fruit, sport, and weather for the sake of convenience.

我要做的是按fruit列对DataFrame进行分组,并将sportweather的相应值放入列表中,以便为它们提供相应的sportweather列表每个唯一的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆