我的数据框如下:
Question
如何按升序遍历日期
id date count
1 2011-01-01 00:00:10 10
1 2011-01-01 00:00:11 12
2 2013-02-02 00:00:01 2
1 2011-01-01 00:00:12 4
2 2014-02-01 00:00:20 6
我的预期结果是:for id, frame in df.groupby('id'):
count_list = []
for item in frame.sort_values(by='date',ascending=True):
count_list.append(item['count'])
答案 0 :(得分:1)
您可以仅按date
进行排序(只要这是正确的datetime
系列),然后按ID
进行分组,然后转换为列表:
# If not already proper date:
df['date'] = pd.to_datetime(df['date'])
df.sort_values(['date']).groupby('id')['count'].apply(list).tolist()
# [[10, 12, 4], [2, 6]]