![](/img/trans.png)
[英]How to pass list of custom functions to pandas.Dataframe.aggregate
[英]How to aggregate an accumulative list in Pandas dataframe?
我有一個 Pandas dataframe 像下面這個。
+--------+-------------------+
| worker | day | tasks |
+--------+-------------------+
| A | 2 | 'read' |
| A | 9 | 'write' |
| B | 1 | 'read' |
| B | 2 | 'write' |
| B | 4 | 'execute' |
+--------+-------------------+
我需要按[col_1, day]對 dataframe 進行分組,並獲得一個累積的任務列表。
例如,如果工人“A”在第 2 天有任務“讀取”,那么第 9 天的任務應該是['read', 'write']列表。
所需的 dataframe 如下所示:
+--------+-------------------------------------+
| worker | day | aggregation |
+--------+-------------------------------------+
| A | 2 | ['read'] |
| A | 9 | ['read', 'write'] |
| B | 1 | ['read'] |
| B | 2 | ['read', 'write'] |
| B | 4 | ['read', 'write', 'execute']|
+--------+-------------------------------------+
我嘗試使用 cumsum
df = df.groupby(['worker', 'day'])['tasks'].apply(list).reset_index(name='aggregation').cumsum()
但它聚合了所有列的累積,而不是特定列的組內。
一種簡單的方法(盡管在性能方面並不理想——然后你再次將列表存儲在列中,因此你的里程會有所不同)是對列表進行groupby
和cumsum
。
df['tasks'].map(lambda x: [x]).groupby(df['worker']).apply(pd.Series.cumsum)
0 [read]
1 [read, write]
2 [read]
3 [read, write]
4 [read, write, execute]
Name: tasks, dtype: object
或者,非常相似,
(df.assign(tasks=df['tasks'].map(lambda x: [x]))
.groupby('worker')['tasks']
.apply(pd.Series.cumsum))
0 [read]
1 [read, write]
2 [read]
3 [read, write]
4 [read, write, execute]
Name: tasks, dtype: object
由於您要對對象(而不是數字數據)進行求和,因此我們需要應用pd.Series.cumsum
而不是調用在GroupBy.cumsum
列表上阻塞的 cythonized GroupBy.cumsum 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.