簡體   English   中英

在多個列列表上應用不同的 Pandas GroupBy 函數

[英]Applying Different Pandas GroupBy Functions on multiple list of columns

我正在尋找一種在列上應用不同 Pandas groupby 函數(如“mean”、“min”或“max”)的方法,具體取決於它們的名稱的開頭。

我目前進行的方式描述如下:

  • 動態創建以 X、Y 或...開頭的列列表
  • 動態創建函數列表以應用於每組列
  • 將列列表及其相應函數合並到字典中
  • 將字典合並到“agg” function 中:
data = np.random.randint(0, 5, (4, 10))
cols = [f"X{i}" if i % 2 == 0 else f"Y{i}" for i in range(10)]

df = pd.DataFrame(data=data, columns=cols)
df["group"] = ["A", "A", "B", "B"]
print(df)

'''
    X0  Y1  X2  Y3  X4  Y5  X6  Y7  X8  Y9 group
0   2   2   1   2   0   4   2   3   0   3     A
1   0   2   1   0   4   2   3   4   4   3     A
2   4   0   1   3   1   3   0   1   2   4     B
3   0   2   1   2   4   0   0   0   4   0     B
'''

col_list_1 = df.filter(like="X").columns
col_list_2 = df.filter(like="Y").columns

list_of_functions_1 = ["mean" for i in range(len(col_list_1))]
list_of_functions_2 = ["min" for i in range(len(col_list_2))]

dict_1 = dict(zip(col_list_1, list_of_functions_1))
dict_2 = dict(zip(col_list_2, list_of_functions_2))

print(df.groupby("group").agg(dict_1 | dict_2))

'''
        X0   X2   X4   X6   X8  Y1  Y3  Y5  Y7  Y9
group
A      1.0  1.0  2.0  2.5  2.0   2   0   2   3   3
B      2.0  1.0  2.5  0.0  3.0   0   2   0   0   0
'''

有沒有更“Pythonic”的方式來做到這一點? 也許是這樣的:

df.groupby("group").agg({col_list_1: "mean",
                         col_list_2: "min"})

謝謝,

皮埃爾-路易

老實說,你這樣做的方式非常pythonic。 如果你想壓縮和自動化它,你可以用嵌套的字典理解來做到這一點:

functions_map = {"X": "mean",
                 "Y": "min"}

df.groupby("group")\
    .agg({variable: stat for prefix, stat in functions_map.items() \
        for variable in df.filter(like=prefix).columns })

'''
        X0   X2   X4   X6   X8  Y1  Y3  Y5  Y7  Y9
group
A      1.0  1.0  2.0  2.5  2.0   2   0   2   3   3
B      2.0  1.0  2.5  0.0  3.0   0   2   0   0   0
'''

暫無
暫無

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

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