聚合操作后解开熊猫数据框

发布于 2025-01-22 20:25:45 字数 312 浏览 2 评论 0原文

我在数据框架上使用了groupby()方法来查找每个位置的总数。我的DataFrame的列是“位置”(城市名称),“名称”(城市中的人的名称)和一个“人”列(每个条目都有一个“ 1”)。

dataframe.groupby(by=['location'], as_index=False)['people'].agg('sum')

在“总和”列的右侧,我需要添加一个列,该列在每个位置列出了所有人的名字(理想情况下是在单独的行中,但列表也很好)。

找到总和后,是否有一种方法可以再次“解开我的数据框架”?

I have used the groupby() method on my dataframe to find the total number of people at each location. My dataframe's columns are "location" (city names), "name" (names of people in the city), and a "people" column (which just has a "1" for each entry).

dataframe.groupby(by=['location'], as_index=False)['people'].agg('sum')

To the right of the "sum" column, I need to add a column that lists all of the people's names at each location (ideally in separate rows, but a list would be fine too).

Is there a way to "ungroup" my dataframe again after having found the sum?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

染火枫林 2025-01-29 20:25:45

您可以做两件不同的事情:

(1)使用groupby.agg并调用适当的方法创建一个汇总数据框。下面的代码列出了与位置相对应的所有名称:

out = dataframe.groupby(by=['location'], as_index=False).agg({'people':'sum', 'name':list})

(2)使用groupby.transform将新列添加到dataframe,该列在每一行中都按位置按位置按位置按位置:

dataframe['sum'] = dataframe.groupby(by=['location'])['people'].transform('sum')

You can do two different things:

(1) Create an aggregate DataFrame using groupby.agg and calling appropriate methods. The code below lists all names corresponding to a location:

out = dataframe.groupby(by=['location'], as_index=False).agg({'people':'sum', 'name':list})

(2) Use groupby.transform to add a new column to dataframe that has the sum of people by location in each row:

dataframe['sum'] = dataframe.groupby(by=['location'])['people'].transform('sum')
你与清晨阳光 2025-01-29 20:25:45

我认为您正在寻找“转型”吗?

dataframe.groupby(by=['location'], as_index=False)['people'].transform('sum')

I think you are looking for 'transform' ?

dataframe.groupby(by=['location'], as_index=False)['people'].transform('sum')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文