簡體   English   中英

Pandas groupby 與 agg 一起使用不返回鍵列

[英]Pandas groupby used with agg doesn't return key columns

在我正在研究的一個項目中,我被迫使用 Pandas 1.1.5 版。 我正在嘗試按操作進行分組,以便使用多個函數聚合變量:

import pandas as pd
import numpy as np

df = pd.DataFrame( { 
        "Name" : ["Alice", "Bob", "James", "Mallory", "Bob" , "Lucas", "Alice", "Bob", "James", "Mallory", "Bob" , "Lucas"] , 
        "Apples" : [22, 31, 35, 41, 27, 32, 64, 12, 59, 45, 65, 31] } )

apple_df = df.groupby('Name', as_index = False).agg(
    apple_avg = ('Apples', np.mean),
    apple_median = ('Apples', np.median),
    apple_count = ('Apples', np.count_nonzero)
)
apple_df

我期望名稱列與其他聚合變量的結果如下:

在此處輸入圖像描述

但我得到以下信息:

在此處輸入圖像描述

此問題的任何已知錯誤和解決方法?

PS All 適用於 Pandas 1.3.0,但我不能在這個項目中使用它。

您可以嘗試刪除 as_index 參數並改為使用 a.reset_index() :

apple_df = df.groupby('Name').agg(
    apple_avg = ('Apples', np.mean),
    apple_median = ('Apples', np.median),
    apple_count = ('Apples', np.count_nonzero)
).reset_index()

暫無
暫無

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

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