本文翻譯自: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"])