【问题标题】:how to smart indexing regard to dates in a data with missing dates in pandas如何智能索引关于熊猫中缺少日期的数据中的日期
【发布时间】:2017-10-17 22:58:20
【问题描述】:

我有一个这样的数据框:

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

【问题讨论】:

  • add and an index column regard to the dates 请详细解释一下。

标签: python pandas date indexing


【解决方案1】:

熊猫.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 分组并应用类似方法来完成。

【讨论】:

    【解决方案2】:

    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
    

    【讨论】:

      猜你喜欢
      • 2016-07-12
      • 1970-01-01
      • 2021-03-19
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多