本文翻译自: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. 如果不设置它,则会得到一个空数据帧。
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
. 聚合函数是减少返回对象的维度的函数,例如:mean
,sum
,size
,count
,std
,var
,sem
,describe
,first
,last
,nth
,min
,max
。 This is what happens when you do for exampleDataFrame.sum()
and get back aSeries
. 当您执行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
及更高版本中,您可以使用count
和reset_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. count
和size
之间的差异是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"])