将 Pandas GroupBy 多索引输出从 Series 转换回 DataFrame

Converting a Pandas GroupBy multiindex output from Series back to DataFrame

提问人:saveenr 提问时间:4/30/2012 最后编辑:smcisaveenr 更新时间:11/18/2023 访问量:1089333

问:

我有一个数据帧:

   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"]).count()

打印时如下所示:

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

但我最终想要的是另一个 DataFrame 对象,它包含 GroupBy 对象中的所有行。换句话说,我想得到以下结果:

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

我该怎么做?

熊猫 数据帧 分组依据 多索引

评论

1赞 Timofey 3/31/2018
抛开问题:你用哪个熊猫版本?如果执行前 2 个命令,我得到 g1 作为Empty DataFrame Columns: [] Index: [(Alice, Seattle), (Bob, Seattle), (Mallory, Portland), (Mallory, Seattle)]

答:

695赞 Wes McKinney 4/30/2012 #1

g1这是一个 DataFrame。不过,它有一个分层索引:

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)

也许你想要这样的东西?

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

或者像这样:

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
190赞 jezrael 8/31/2015 #2

我想稍微改变一下 Wes 给出的答案,因为 0.16.2 版本需要 .如果不设置它,则会得到一个空的数据帧。as_index=False

来源

如果要聚合的组被命名为列,则聚合函数不会返回这些组,当 时,默认值为 。分组的列将是返回对象的索引。as_index=True

传递将返回要聚合的组(如果这些组名为列)。as_index=False

聚合函数是减少返回对象维度的函数,例如:、、、例如,当您这样做并返回 .meansumsizecountstdvarsemdescribefirstlastnthminmaxDataFrame.sum()Series

第 n 个可以充当减速器或过滤器,请参阅此处

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
#

编辑:

在版本及更高版本中,您可以在 countreset_index 中使用 size 参数:0.17.1subsetname

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

和 之间的区别在于计算 NaN 值,而不计算。countsizesizecount

8赞 thefebruaryman 4/29/2016 #3

我发现这对我有用。

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()
36赞 Surya 4/30/2016 #4

简单地说,这应该可以完成任务:

import pandas as pd

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

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

在这里,拉出唯一的 groupby 计数,方法重置您希望它成为的列的名称。 最后,调用 pandas 函数来创建一个 DataFrame 对象。grouped_df.size()reset_index()Dataframe()

15赞 brandog 4/1/2017 #5

也许我误解了这个问题,但如果你想将 groupby 转换回数据帧,你可以使用 .to_frame()。当我这样做时,我想重置索引,所以我也包括了那部分。

与问题无关的示例代码

df = df['TIME'].groupby(df['Name']).min()
df = df.to_frame()
df = df.reset_index(level=['Name',"TIME"])
5赞 Manivannan Murugavel 12/18/2017 #6

我已经用数量明智的数据进行了聚合并存储到 dataframe

almo_grp_data = pd.DataFrame({'Qty_cnt' :
almo_slt_models_data.groupby( ['orderDate','Item','State Abv']
          )['Qty'].sum()}).reset_index()
4赞 Josh Weston 7/14/2018 #7

这些解决方案只对我有用,因为我正在做多个聚合。以下是我想转换为数据帧的分组者的示例输出:

Groupby Output

因为我想要的不仅仅是 reset_index() 提供的计数,所以我编写了一个手动方法,用于将上面的图像转换为数据帧。我知道这不是最蟒蛇/熊猫的方式,因为它非常冗长和明确,但这就是我所需要的。基本上,使用上面解释的 reset_index() 方法启动“脚手架”数据帧,然后遍历分组数据帧中的组配对,检索索引,针对未分组的数据帧执行计算,并在新的聚合数据帧中设置值。

df_grouped = df[['Salary Basis', 'Job Title', 'Hourly Rate', 'Male Count', 'Female Count']]
df_grouped = df_grouped.groupby(['Salary Basis', 'Job Title'], as_index=False)

# Grouped gives us the indices we want for each grouping
# We cannot convert a groupedby object back to a dataframe, so we need to do it manually
# Create a new dataframe to work against
df_aggregated = df_grouped.size().to_frame('Total Count').reset_index()
df_aggregated['Male Count'] = 0
df_aggregated['Female Count'] = 0
df_aggregated['Job Rate'] = 0

def manualAggregations(indices_array):
    temp_df = df.iloc[indices_array]
    return {
        'Male Count': temp_df['Male Count'].sum(),
        'Female Count': temp_df['Female Count'].sum(),
        'Job Rate': temp_df['Hourly Rate'].max()
    }

for name, group in df_grouped:
    ix = df_grouped.indices[name]
    calcDict = manualAggregations(ix)

    for key in calcDict:
        #Salary Basis, Job Title
        columns = list(name)
        df_aggregated.loc[(df_aggregated['Salary Basis'] == columns[0]) & 
                          (df_aggregated['Job Title'] == columns[1]), key] = calcDict[key]

如果字典不是你的事,可以在 for 循环中内联应用计算:

    df_aggregated['Male Count'].loc[(df_aggregated['Salary Basis'] == columns[0]) & 
                                (df_aggregated['Job Title'] == columns[1])] = df['Male Count'].iloc[ix].sum()
7赞 Xiao QianYu 8/28/2018 #8

以下解决方案可能更简单:

df1.reset_index().groupby( [ "Name", "City"],as_index=False ).count()
73赞 Ferd 3/28/2019 #9

关键是使用 reset_index() 方法。

用:

import pandas

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

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

现在,您在 g1 中拥有了新的数据帧:

result dataframe

1赞 Golden Lion 2/3/2021 #10
 grouped=df.groupby(['Team','Year'])['W'].count().reset_index()

 team_wins_df=pd.DataFrame(grouped)
 team_wins_df=team_wins_df.rename({'W':'Wins'},axis=1)
 team_wins_df['Wins']=team_wins_df['Wins'].astype(np.int32)
 team_wins_df.reset_index()
 print(team_wins_df)
7赞 Edison 6/8/2022 #11

这将以与普通方法相同的顺序返回序号级别/索引。它与@NehalJWani在他的评论中发布的答案基本相同,但存储在一个变量中,并调用了该变量。groupby()reset_index()

fare_class = df.groupby(['Satisfaction Rating','Fare Class']).size().to_frame(name = 'Count')
fare_class.reset_index()

此版本不仅返回具有百分比的相同数据,这对统计很有用,而且还包括一个 lambda 函数。

fare_class_percent = df.groupby(['Satisfaction Rating', 'Fare Class']).size().to_frame(name = 'Percentage')
fare_class_percent.transform(lambda x: 100 * x/x.sum()).reset_index()

      Satisfaction Rating      Fare Class  Percentage
0            Dissatisfied        Business   14.624269
1            Dissatisfied         Economy   36.469048
2               Satisfied        Business    5.460425
3               Satisfied         Economy   33.235294

例:enter image description here

0赞 rram12 8/3/2022 #12

尝试在 group_by 方法中设置 group_keys=False,以防止将组键添加到索引中。

例:

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.groupby(["Name"], group_keys=False)
0赞 cottontail 11/3/2023 #13

.reset_index()方法/参数as_index=False

在大多数实际情况下,这两种变体的行为是相同的。其实如果我们看一下groupby的源码,对于某些方法来说,字面上是等价的。as_index=Falsereset_index()

# sample data
df = pd.DataFrame({
    'A': ['g1', 'g1', 'g2', 'g2'], 
    'B': [1, 1, 2, 2],
    'C': [1, 2, 3, 4]
})

y1 = df.groupby(['A', 'B'], as_index=False)['C'].sum()
y2 = df.groupby(['A', 'B'])['C'].sum().reset_index()
y1.equals(y2)   # True

最终,进行以下转换(并且通过完全避免左侧的系列)。请注意,它会创建一个 3 列(石斑列数 + 正在聚合的列)数据帧。reset_index()as_index=False

result1

reset_index如果石斑鱼中使用的列也在输出中(如在 OP 中),则行为不同。在这种情况下,从石斑鱼中删除所有重叠的列(通过 _insert_inaxis_grouper 方法)。下面的示例说明了这一点。as_index=Falseas_index=False

df = pd.DataFrame({'A': ['g1', 'g1', 'g2', 'g2'], 'B': [1, 1, 2, 2]})

df.groupby(['A', 'B'])['B'].sum()                           # <--- includes B as a grouper
df.groupby(['A', 'B'])['B'].sum().reset_index(name='Total') # <--- includes B as a grouper
df.groupby(['A', 'B'], as_index=False)['B'].sum()           # <--- drops B from the grouper

differing case

.to_frame()方法 / 在列列表中groupby.method

to_frame()方法将 Series 转换为 DataFrame,其中将石组保留为索引,并将 Series 中的值转换为 DataFrame 列。您可以选择传递聚合列的名称。但是,如果未传递 name,则与简单地在 groupby 的列列表中调用聚合器函数完全相同。

x1 = df.groupby(['A', 'B'])['C'].sum().to_frame()
x2 = df.groupby(['A', 'B'])[['C']].sum()
#                          ^^   ^^  <--- list of columns
x1.equals(x2)   # True


# if `name=` is passed, it can rename the aggregated column in one go
x3 = df.groupby(['A', 'B'])['C'].sum().to_frame('Total')
x4 = df.groupby(['A', 'B'])[['C']].sum().rename(columns={'C': 'Total'})
x3.equals(x4)   # True

最终,进行以下转换(并且传递要聚合的列列表完全避免了左侧的序列)。请注意,与 不同,它创建单列数据帧。to_frame(name)reset_index()

result2


最后,至少从 pandas 0.16.2 开始,方法(OP 中的特定方法)返回一个空的数据帧。但是,每次拆分的调用计数都会恢复聚合计数。正如 jezrael 的回答中提到的,列出所有聚合列也可以,但如果有很多列,这种情况可能更具可读性。groupby.countgroupbygroupby.agg

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

df1.groupby(['Name', 'City']).count()                   # empty dataframe
df1.groupby(['Name', 'City']).agg(lambda x: x.count())  # OK

result3