将Pandas GroupBy输出从Series转换为DataFrame

我从这样的输入数据开始

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

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

                  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

以上是 将Pandas GroupBy输出从Series转换为DataFrame 的全部内容, 来源链接: utcz.com/qa/434597.html

回到顶部