[英]Converting a Pandas GroupBy output from Series to 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
object:
City Name
Name City
Alice Seattle 1 1
Bob Seattle 2 2
Mallory Portland 2 2
Seattle 1 1
但我最終想要的是另一個 DataFrame object 包含 GroupBy object 中的所有行。 換句話說,我想得到以下結果:
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
我想稍微改變一下 Wes 給出的答案,因為 0.16.2 版本需要as_index=False
。 如果你不設置它,你會得到一個空的數據框。
來源:
如果聚合函數被命名為列,則聚合函數將不會返回您聚合的組,當
as_index=True
時,默認值。 分組列將是返回對象的索引。傳遞
as_index=False
將返回您正在聚合的組,如果它們是命名列。聚合函數是減少返回對象維度的函數,例如:
mean
、sum
、size
、count
、std
、var
、sem
、describe
、first
、last
、nth
、min
、max
。 例如,當您執行DataFrame.sum()
並取回Series
時,就會發生這種情況。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
#
編輯:
在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
count
和size
之間的區別在於size
計算 NaN 值,而count
不計算。
關鍵是使用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中有新的數據框:
簡單地說,這應該完成任務:
import pandas as pd
grouped_df = df1.groupby( [ "Name", "City"] )
pd.DataFrame(grouped_df.size().reset_index(name = "Group_Count"))
在這里, grouped_df.size()
提取唯一的 groupby 計數,而reset_index()
方法重置您想要的列的名稱。 最后,調用 pandas Dataframe()
函數來創建 DataFrame 對象。
也許我誤解了這個問題,但如果你想將 groupby 轉換回數據框,你可以使用 .to_frame()。 我想在執行此操作時重置索引,所以我也包含了該部分。
與問題無關的示例代碼
df = df['TIME'].groupby(df['Name']).min()
df = df.to_frame()
df = df.reset_index(level=['Name',"TIME"])
我發現這對我有用。
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()
以下解決方案可能更簡單:
df1.reset_index().groupby( [ "Name", "City"],as_index=False ).count()
我已經匯總了數量明智的數據並存儲到數據框
almo_grp_data = pd.DataFrame({'Qty_cnt' :
almo_slt_models_data.groupby( ['orderDate','Item','State Abv']
)['Qty'].sum()}).reset_index()
這些解決方案僅對我部分有效,因為我正在進行多次聚合。 這是我想要轉換為數據框的分組示例輸出:
因為我想要的不僅僅是 reset_index() 提供的計數,所以我編寫了一個手動方法來將上面的圖像轉換為數據幀。 我知道這不是最 Pythonic/pandas 的方式,因為它非常冗長和明確,但這就是我所需要的。 基本上,使用上面解釋的 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()
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)
這會以與groupby()
方法相同的順序返回序數級別/索引。 它與@NehalJWani 在他的評論中發布的答案基本相同,但存儲在一個變量中,並調用了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
嘗試在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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.