簡體   English   中英

從 Pandas groupby 對象中選擇多個組

[英]Select multiple groups from pandas groupby object

我正在試驗熊貓的 groupby 功能,特別是

gb = df.groupby('model')
gb.hist()

由於 gb 有 50 個組,結果非常混亂,我只想探索前 5 個組的結果。

我找到了如何使用groupsget_group選擇單個組(如何通過鍵訪問熊貓 groupby 數據get_group ),但沒有找到如何直接選擇多個組。 我能做的最好的是:

groups = dict(list(gb))
subgroup = pd.concat(groups.values()[:4])
subgroup.groupby('model').hist()

有沒有更直接的方法?

首先過濾 df 然后執行groupby會更容易:

In [155]:

df = pd.DataFrame({'model':np.random.randint(1,10,100), 'value':np.random.randn(100)})
first_five = df['model'].sort(inplace=False).unique()[:5]
gp = df[df['model'].isin(first_five)].groupby('model')
gp.first()
Out[155]:
          value
model          
1     -0.505677
2      1.217027
3     -0.641583
4      0.778104
5     -1.037858

你可以做類似的事情

new_gb = pandas.concat( [ gb.get_group(group) for i,group in enumerate( gb.groups) if i < 5 ] ).groupby('model')    
new_gb.hist()

雖然,我會以不同的方式處理它。 您可以使用collections.Counter對象快速獲取組:

import collections

df = pandas.DataFrame.from_dict({'model': pandas.np.random.randint(0, 3, 10), 'param1': pandas.np.random.random(10), 'param2':pandas.np.random.random(10)})
#   model    param1    param2
#0      2  0.252379  0.985290
#1      1  0.059338  0.225166
#2      0  0.187259  0.808899
#3      2  0.773946  0.696001
#4      1  0.680231  0.271874
#5      2  0.054969  0.328743
#6      0  0.734828  0.273234
#7      0  0.776684  0.661741
#8      2  0.098836  0.013047
#9      1  0.228801  0.827378
model_groups = collections.Counter(df.model)
print(model_groups) #Counter({2: 4, 0: 3, 1: 3})

現在您可以像字典一樣遍歷Counter對象,並查詢您想要的組:

new_df = pandas.concat( [df.query('model==%d'%key) for key,val in model_groups.items() if val < 4 ] ) # for example, but you can select the models however you like  
#   model    param1    param2
#2      0  0.187259  0.808899
#6      0  0.734828  0.273234
#7      0  0.776684  0.661741
#1      1  0.059338  0.225166
#4      1  0.680231  0.271874
#9      1  0.228801  0.827378

現在您可以使用內置的pandas.DataFrame.groupby函數

gb = new_df.groupby('model')
gb.hist() 

由於model_groups包含所有組,您可以根據需要從中選擇。

筆記

如果您的model列包含字符串值(名稱或其他內容)而不是整數,則它的工作方式都相同 - 只需將查詢參數從'model==%d'%key更改為'model=="%s"'%key .

我不知道有什么方法可以將.get_group()方法用於多個組。

但是,您可以遍歷組

這樣做仍然有點難看,但這是一個迭代的解決方案:

limit = 5
i = 0
for key, group in gd:
    print key, group
    i += 1
    if i >= limit:
        break

你也可以用.get_group()做一個循環,恕我直言。 有點漂亮,但仍然很丑。

for key in gd.groups.keys()[:2]:
    print gd.get_group(key)
gbidx=list(gb.indices.keys())[:4]
dfidx=np.sort(np.concatenate([gb.indices[x] for x in gbidx]))
df.loc[dfidx].groupby('model').hist()

gb.indices 比 gb.groups 或 list(gb) 快

我相信 concat Index 比 concat DataFrames 快

我已經嘗試過我的 ~416M 行 13 列(包括 str)和 720MB 大小的大 csv 文件,並且通過多個列進行分組

然后將 col 名稱更改為問題中的名稱

def get_groups(group_object):
    for i in group_object.groups.keys():
        print(f"____{i}____")
        display(group_object.get_group(i))


#get all groups by calling this method 

get_groups( any_group_which_you_made )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM