2017-10-17 49 views
0

我有这样一个数据帧丢失日期:如何智能索引关于日期的数据与熊猫

id  date  value 
1  2017-01-01 10 
1  2017-01-01 20 
1  2017-01-02 10 
1  2017-01-02 15 
1  2017-01-07 25 
2  2017-05-01 10 
2  2017-05-01 15 
2  2017-05-20 30 
3  2010-08-08 40 
3  2010-08-11 20 
3  2010-08-11 43 

我想每个日期添加值,并添加和索引列关于例如日期,最后的数据应该是这样的:

id  date  value index 
1  2017-01-01 30  1 
1  2017-01-02 25  2 
1  2017-01-07 25  3 
2  2017-05-01 25  1 
2  2017-05-20 30  2 
3  2010-08-08 40  1 
3  2010-08-11 63  2 
+0

'添加和索引列关于dates'请更详细地说明这一点。 –

回答

1

sumcumcount

df1=df.groupby(['id','date'],as_index=False).value.sum() 
df1['index']=df1.groupby('id',as_index=False).cumcount().add(1) 
df1 
Out[167]: 
    id  date value index 
0 1 2017-01-01  30  1 
1 1 2017-01-02  25  2 
2 1 2017-01-07  25  3 
3 2 2017-05-01  25  1 
4 2 2017-05-20  30  2 
5 3 2010-08-08  40  1 
6 3 2010-08-11  63  2 
2

熊猫.groupby()是你的朋友。

>>> df 
    id  date value 
0 1 2017-01-01  10 
1 1 2017-01-01  20 
2 1 2017-01-02  10 
3 1 2017-01-02  15 
4 1 2017-01-07  25 
5 2 2017-05-01  10 
6 2 2017-05-01  15 
7 2 2017-05-20  30 
8 3 2010-08-08  40 
9 3 2010-08-11  20 
10 3 2010-08-11  43 

按日期和id对数据进行分组,使其不会与.sum()相加。 as_index=False使得日期列不会成为索引。 sort=False使它不会按日期排序。

>>> g = df.groupby(['date', 'id'], as_index=False, sort=False).sum() 
>>> g 
     date id value 
2 2017-01-01 1  30 
3 2017-01-02 1  25 
4 2017-01-07 1  25 
5 2017-05-01 2  25 
6 2017-05-20 2  30 
0 2010-08-08 3  40 
1 2010-08-11 3  63 

这是一个有点暧昧,你第二部分的意思,但假设它意味着同等IDS的累积和:

>>> g['index'] = g.assign(count=1).groupby('id').cumsum()['count'] 
>>> g 
     date id value index 
2 2017-01-01 1  30  1 
3 2017-01-02 1  25  2 
4 2017-01-07 1  25  3 
5 2017-05-01 2  25  1 
6 2017-05-20 2  30  2 
0 2010-08-08 3  40  1 
1 2010-08-11 3  63  2 

这里我们分配g['index']count列的累积和我们给每个元素的数据帧等于1。

如果你实际上的意思是每个类似月份的累计总和,可以通过df.date.dt.month分组并且应用类似的方法来完成。

+0

谢谢!这是我想要的 – ary