将Pandas GroupBy输出从Series转换为DataFrame

本文翻译自:Converting a Pandas GroupBy output from Series to DataFrame

I'm starting with input data like this 我从这样的输入数据开始

df1 = pandas.DataFrame( { 
    "Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] , 
    "City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"] } )

Which when printed appears as this: 打印时显示如下:

   City     Name
0   Seattle    Alice
1   Seattle      Bob
2  Portland  Mallory
3   Seattle  Mallory
4   Seattle      Bob
5  Portland  Mallory

Grouping is simple enough: 分组很简单:

g1 = df1.groupby( [ "Name", "City"] ).count()

and printing yields a GroupBy object: 和打印产生一个GroupBy对象:

                  City  Name
Name    City
Alice   Seattle      1     1
Bob     Seattle      2     2
Mallory Portland     2     2
        Seattle      1     1

But what I want eventually is another DataFrame object that contains all the rows in the GroupBy object. 但我最终想要的是另一个包含GroupBy对象中所有行的DataFrame对象。 In other words I want to get the following result: 换句话说,我希望得到以下结果:

                  City  Name
Name    City
Alice   Seattle      1     1
Bob     Seattle      2     2
Mallory Portland     2     2
Mallory Seattle      1     1

I can't quite see how to accomplish this in the pandas documentation. 我无法在pandas文档中看到如何实现这一点。 Any hints would be welcome. 任何提示都会受到欢迎。


#1楼

参考:https://stackoom.com/question/hWf6/将Pandas-GroupBy输出从Series转换为DataFrame


#2楼

g1 here is a DataFrame. g1这里一个DataFrame。 It has a hierarchical index, though: 它有一个分层索引,但是:

In [19]: type(g1)
Out[19]: pandas.core.frame.DataFrame

In [20]: g1.index
Out[20]: 
MultiIndex([('Alice', 'Seattle'), ('Bob', 'Seattle'), ('Mallory', 'Portland'),
       ('Mallory', 'Seattle')], dtype=object)

Perhaps you want something like this? 也许你想要这样的东西?

In [21]: g1.add_suffix('_Count').reset_index()
Out[21]: 
      Name      City  City_Count  Name_Count
0    Alice   Seattle           1           1
1      Bob   Seattle           2           2
2  Mallory  Portland           2           2
3  Mallory   Seattle           1           1

Or something like: 或类似的东西:

In [36]: DataFrame({'count' : df1.groupby( [ "Name", "City"] ).size()}).reset_index()
Out[36]: 
      Name      City  count
0    Alice   Seattle      1
1      Bob   Seattle      2
2  Mallory  Portland      2
3  Mallory   Seattle      1

#3楼

I want to slightly change the answer given by Wes, because version 0.16.2 requires as_index=False . 我想略微改变Wes给出的答案,因为版本0.16.2需要as_index=False If you don't set it, you get an empty dataframe. 如果不设置它,则会得到一个空数据帧。

Source : 来源

Aggregation functions will not return the groups that you are aggregating over if they are named columns, when as_index=True , the default. 如果as_index=True ,则聚合函数将不会返回聚合的组(如果它们是命名列)。 The grouped columns will be the indices of the returned object. 分组列将是返回对象的索引。

Passing as_index=False will return the groups that you are aggregating over, if they are named columns. 传递as_index=False将返回您聚合的组(如果它们是命名列)。

Aggregating functions are ones that reduce the dimension of the returned objects, for example: mean , sum , size , count , std , var , sem , describe , first , last , nth , min , max . 聚合函数是减少返回对象的维度的函数,例如: meansumsizecountstdvarsemdescribefirstlastnthminmax This is what happens when you do for example DataFrame.sum() and get back a Series . 当您执行DataFrame.sum()并返回Series时会发生这种情况。

nth can act as a reducer or a filter, see here . nth可以作为减速器或过滤器,请参见此处

import pandas as pd

df1 = pd.DataFrame({"Name":["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"],
                    "City":["Seattle","Seattle","Portland","Seattle","Seattle","Portland"]})
print df1
#
#       City     Name
#0   Seattle    Alice
#1   Seattle      Bob
#2  Portland  Mallory
#3   Seattle  Mallory
#4   Seattle      Bob
#5  Portland  Mallory
#
g1 = df1.groupby(["Name", "City"], as_index=False).count()
print g1
#
#                  City  Name
#Name    City
#Alice   Seattle      1     1
#Bob     Seattle      2     2
#Mallory Portland     2     2
#        Seattle      1     1
#

EDIT: 编辑:

In version 0.17.1 and later you can use subset in count and reset_index with parameter name in size : 0.17.1及更高版本中,您可以使用countreset_index subset ,其size为参数name

print df1.groupby(["Name", "City"], as_index=False ).count()
#IndexError: list index out of range

print df1.groupby(["Name", "City"]).count()
#Empty DataFrame
#Columns: []
#Index: [(Alice, Seattle), (Bob, Seattle), (Mallory, Portland), (Mallory, Seattle)]

print df1.groupby(["Name", "City"])[['Name','City']].count()
#                  Name  City
#Name    City                
#Alice   Seattle      1     1
#Bob     Seattle      2     2
#Mallory Portland     2     2
#        Seattle      1     1

print df1.groupby(["Name", "City"]).size().reset_index(name='count')
#      Name      City  count
#0    Alice   Seattle      1
#1      Bob   Seattle      2
#2  Mallory  Portland      2
#3  Mallory   Seattle      1

The difference between count and size is that size counts NaN values while count does not. countsize之间的差异是size计算NaN值而count不计算NaN值。


#4楼

I found this worked for me. 我发现这对我有用。

import numpy as np
import pandas as pd

df1 = pd.DataFrame({ 
    "Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] , 
    "City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"]})

df1['City_count'] = 1
df1['Name_count'] = 1

df1.groupby(['Name', 'City'], as_index=False).count()

#5楼

Simply, this should do the task: 简单地说,这应该完成任务:

import pandas as pd

grouped_df = df1.groupby( [ "Name", "City"] )

pd.DataFrame(grouped_df.size().reset_index(name = "Group_Count"))

Here, grouped_df.size() pulls up the unique groupby count, and reset_index() method resets the name of the column you want it to be. 这里,grouped_df.size()提取唯一的groupby计数,reset_index()方法重置你想要的列的名称。 Finally, the pandas Dataframe() function is called upon to create DataFrame object. 最后,调用pandas Dataframe()函数来创建DataFrame对象。


#6楼

Maybe I misunderstand the question but if you want to convert the groupby back to a dataframe you can use .to_frame(). 也许我误解了这个问题,但如果你想将groupby转换回数据帧,你可以使用.to_frame()。 I wanted to reset the index when I did this so I included that part as well. 当我这样做时,我想重置索引,所以我也包括了那部分。

example code unrelated to question 示例代码与问题无关

df = df['TIME'].groupby(df['Name']).min()
df = df.to_frame()
df = df.reset_index(level=['Name',"TIME"])
  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值