python - 将 Pandas GroupBy 输出从 Series 转换为 DataFrame

标签 python pandas dataframe pandas-groupby multi-index

我从这样的输入数据开始

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

打印出来的时候是这样的:

   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()

并且打印会产生一个 GroupBy 对象:

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

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

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

我不太明白如何在 pandas 文档中完成此操作。欢迎任何提示。

最佳答案

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

关于python - 将 Pandas GroupBy 输出从 Series 转换为 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10373660/

相关文章:

python - 有没有办法遍历模块的所有功能?

python - python "with"命令可以用于选择性地写入文件

python - 删除具有空值的选定行的行

python - Pandas 试图通过获取某些字符串之间的行来转换数据框

python - python 中列的模式匹配

python - 是否有 "get or default"访问列表的方式?

python - 在 Idle shell 中导入模块

python - 将值添加到数据框列中的最大值

python - 如何将新列作为字符串分配给 Pandas 分配

python - Pandas - 从行数中获取汇总数据框