[英]Pandas aggregate list in resample/groupby
我有一個數據幀,其中每個實例都有一個時間戳、一個 id 和一個數字列表,如下所示:
timestamp | id | lists
----------------------------------
2016-01-01 00:00:00 | 1 | [2, 10]
2016-01-01 05:00:00 | 1 | [9, 10, 3, 5]
2016-01-01 10:00:00 | 1 | [1, 10, 5]
2016-01-02 01:00:00 | 1 | [2, 6, 7]
2016-01-02 04:00:00 | 1 | [2, 6]
2016-01-01 02:00:00 | 2 | [0]
2016-01-01 08:00:00 | 2 | [10, 3, 2]
2016-01-01 14:00:00 | 2 | [0, 9, 3]
2016-01-02 03:00:00 | 2 | [0, 9, 2]
對於每個id,我想按天重新采樣(這很容易)並連接同一天發生的所有實例列表。 Resample + concat/sum 不起作用,因為 resample 刪除了所有非數字列( 請參閱此處)
我想寫一些類似的東西:
daily_data = data.groupby('id').resample('1D').concatenate() # .concatenate() does not exist
想要的結果:
timestamp | id | lists
----------------------------------
2016-01-01 | 1 | [2, 10, 9, 10, 3, 5, 1, 10, 5]
2016-01-02 | 1 | [2, 6, 7, 2, 6]
2016-01-01 | 2 | [0, 10, 3, 2]
2016-01-02 | 2 | [0, 9, 3, 0, 9, 2]
在這里,您可以復制一個腳本來生成我用於描述的輸入:
import pandas as pd
from random import randint
time = pd.to_datetime( ['2016-01-01 00:00:00', '2016-01-01 05:00:00',
'2016-01-01 10:00:00', '2016-01-02 01:00:00',
'2016-01-02 04:00:00', '2016-01-01 02:00:00',
'2016-01-01 08:00:00', '2016-01-01 14:00:00',
'2016-01-02 03:00:00' ]
)
id_1 = [1] * 5
id_2 = [2] * 4
lists = [0] * 9
for i in range(9):
l = [randint(0,10) for _ in range(randint(1,5) ) ]
l = list(set(l))
lists[i] = l
data = {'timestamp': time, 'id': id_1 + id_2, 'lists': lists}
example = pd.DataFrame(data=data)
如果有一種方法可以選擇性地刪除連接列表中的重復項,則加分。
對於每個列表項的唯一計數,請使用列表理解:
a = [list(set(l)) for l in df.lists]
df.loc[:,'lists'] = a
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.