[英]pandas groupby without turning grouped by column into index
pandas groupby 的默認行為是將 group by 列轉換為索引,並將它們從數據框的列列表中刪除。 例如,假設我有一個包含這些列的數據框
col1|col2|col3|col4
如果我以這種方式應用 groupby 列col2
和col3
df.groupby(['col2','col3']).sum()
數據框df
在列列表中不再具有['col2','col3']
。 它們會自動變成結果數據幀的索引。
我的問題是如何在列上執行 groupby 並將該列保留在數據框中?
df.groupby(['col2','col3'], as_index=False).sum()
另一種方法是:
df.groupby(['col2', 'col3']).sum().reset_index()
添加了以下稍微詳細的答案以幫助那些仍然對使用哪種答案變體感到困惑的人。
首先,針對此問題提出的兩種解決方案是:
df.groupby(['A', 'B'], as_index=False).sum()
df.groupby(['A', 'B']).sum().reset_index()
兩者都給出了預期的結果。
如文檔中所述, as_index
將要求SQL 樣式的分組輸出,這將有效地要求 pandas 在輸出中保留這些按列分組的輸出。
as_index : bool,默認為 True
對於聚合輸出,返回以組標簽為索引的對象。 僅與 DataFrame 輸入相關。 as_index=False 實際上是“SQL 風格”的分組輸出。
例子:
給定以下數據框:
A B C D
0 A 1 0.502130 0.959404
1 A 3 0.335416 0.087215
2 B 2 0.067308 0.084595
3 B 4 0.454158 0.723124
4 B 4 0.323326 0.895858
5 C 2 0.672375 0.356736
6 C 5 0.929655 0.371913
7 D 5 0.212634 0.540736
8 D 5 0.471418 0.268270
9 E 1 0.061270 0.739610
應用第一個解決方案給出:
>>> df.groupby(["A", "B"], as_index=False).sum()
A B C D
0 A 1 0.502130 0.959404
1 A 3 0.335416 0.087215
2 B 2 0.067308 0.084595
3 B 4 0.777483 1.618982
4 C 2 0.672375 0.356736
5 C 5 0.929655 0.371913
6 D 5 0.684052 0.809006
7 E 1 0.061270 0.739610
正確保留 groupby 列的位置。
要理解第二種解決方案,讓我們看一下as_index = True
上一個命令的輸出,這是pandas.DataFrame.groupby
的默認行為(查看文檔):
>>> df.groupby(["A", "B"], as_index=True).sum()
C D
A B
A 1 0.502130 0.959404
3 0.335416 0.087215
B 2 0.067308 0.084595
4 0.777483 1.618982
C 2 0.672375 0.356736
5 0.929655 0.371913
D 5 0.684052 0.809006
E 1 0.061270 0.739610
如您所見,groupby 鍵成為數據幀的索引。 使用pandas.DataFrame.reset_index
(查看文檔),我們可以將數據幀的索引作為列放回並使用默認索引。 這也使我們得到與上一步相同的結果:
>>> df.groupby(['A', 'B']).sum().reset_index()
A B C D
0 A 1 0.502130 0.959404
1 A 3 0.335416 0.087215
2 B 2 0.067308 0.084595
3 B 4 0.777483 1.618982
4 C 2 0.672375 0.356736
5 C 5 0.929655 0.371913
6 D 5 0.684052 0.809006
7 E 1 0.061270 0.739610
請注意,由於第一個解決方案在 1 步中實現了要求,而在第二個解決方案中實現了 2 個步驟,因此前者稍微快一些:
%timeit df.groupby(["A", "B"], as_index=False).sum()
3.38 ms ± 21.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit df.groupby(["A", "B"]).sum().reset_index()
3.9 ms ± 365 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
不確定,但我認為正確的答案是
df.groupby(['col2','col3']).sum()
df = df.reset_index()
至少我一直在做的是避免使用多索引的數據幀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.