【问题标题】:How do I create a period range of months and fill it with zeroes?如何创建一个月份的周期范围并用零填充?
【发布时间】:2020-07-21 11:40:35
【问题描述】:

假设我有一个数据框,其中包含每个月发生的某些事件。数据仅包含事件的月份和年份以及每月发生的事件数量。

df = pd.DataFrame({'month':['2018-01', '2018-02', '2018-04','2018-05','2018-06', 
                            '2018-07', '2018-10','2018-11', '2019-01', '2019-02',
                            '2019-03', '2019-05','2019-07', '2019-11', '2019-12'],
                  'counts':[10,5,6,1,2,5,7,8,9,1,10,12,8,10,4]})

df
    month  counts
0   2018-01 10
1   2018-02 5
2   2018-04 6
3   2018-05 1
4   2018-06 2
5   2018-07 5
6   2018-10 7
7   2018-11 8
8   2019-01 9
9   2019-02 1
10  2019-03 10
11  2019-05 12
12  2019-07 10
13  2019-11 10
14  2019-12 4

正如您在上面注意到的,2018 年 1 月到 2019 年 12 月之间有一个时间范围,但并非所有月份都有计数值。例如,没有 2018 年 3 月 (2018-03) 的数据,并且它们之间有许多缺失的月份。

我想把这个缺失的月份填上零,所以基本上我想以正确的顺序插入{'month':'2018-03', count:0}。我也想对所有缺失的月份和应该存在的值做同样的事情。

我所做的如下。

我将月份转换为适当的格式。

df['month'] = pd.to_datetime(df['month']).dt.to_period('M')

上面的代码运行良好。

然后我尝试以每月频率创建一个日期范围,但这不起作用。

idx = pd.date_range(min(df['month']), max(df['month']), freq='M)

错误提示ValueError: Cannot convert Period to Timestamp unambiguously. Use to_timestamp

我该怎么办?谢谢。

【问题讨论】:

标签: python pandas datetime


【解决方案1】:

使用period_range,然后将句点列转换为PeriodIndex并使用DataFrame.reindex

df['month'] = pd.to_datetime(df['month']).dt.to_period('M')
idx = pd.period_range(df['month'].min(), df['month'].max(), freq='M')
df = df.set_index('month').reindex(idx, fill_value=0)
print (df)
         counts
2018-01      10
2018-02       5
2018-03       0
2018-04       6
2018-05       1
2018-06       2
2018-07       5
2018-08       0
2018-09       0
2018-10       7
2018-11       8
2018-12       0
2019-01       9
2019-02       1
2019-03      10
2019-04       0
2019-05      12
2019-06       0
2019-07       8
2019-08       0
2019-09       0
2019-10       0
2019-11      10
2019-12       4

【讨论】:

  • 有趣!我不知道pd.period_range 存在。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 2014-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-21
相关资源
最近更新 更多