通过用 0 填充缺失的月份来获取 pandas 中的连续数据帧
Get continuous dataframe in pandas by filling the missing month with 0
我有一个 pandas 数据框,如下所示,其中我有月-年,需要获取连续数据框,如果找不到该月的行,它应该包括计数为 0。异常输出如下所示。
输入数据帧
Month | Count
--------------
Jan-15 | 10
Feb-15 | 100
Mar-15 | 20
Jul-15 | 10
Sep-15 | 11
Oct-15 | 1
Dec-15 | 15
预期输出
Month | Count
--------------
Jan-15 | 10
Feb-15 | 100
Mar-15 | 20
Apr-15 | 0
May-15 | 0
Jun-15 | 0
Jul-15 | 10
Aug-15 | 0
Sep-15 | 11
Oct-15 | 1
Nov-15 | 0
Dec-15 | 15
您可以将月份列设置为索引。它看起来像 Excel 输入,如果是这样,它将在 2015 年 1 月 1 日被解析,因此您可以按如下方式重新采样:
df.set_index('Month').resample('MS').asfreq().fillna(0)
Out:
Count
Month
2015-01-01 10.0
2015-02-01 100.0
2015-03-01 20.0
2015-04-01 0.0
2015-05-01 0.0
2015-06-01 0.0
2015-07-01 10.0
2015-08-01 0.0
2015-09-01 11.0
2015-10-01 1.0
2015-11-01 0.0
2015-12-01 15.0
如果月份列不能识别为日期,需要先进行转换:
df['Month'] = pd.to_datetime(df['Month'], format='%b-%y')
我有一个 pandas 数据框,如下所示,其中我有月-年,需要获取连续数据框,如果找不到该月的行,它应该包括计数为 0。异常输出如下所示。
输入数据帧
Month | Count
--------------
Jan-15 | 10
Feb-15 | 100
Mar-15 | 20
Jul-15 | 10
Sep-15 | 11
Oct-15 | 1
Dec-15 | 15
预期输出
Month | Count
--------------
Jan-15 | 10
Feb-15 | 100
Mar-15 | 20
Apr-15 | 0
May-15 | 0
Jun-15 | 0
Jul-15 | 10
Aug-15 | 0
Sep-15 | 11
Oct-15 | 1
Nov-15 | 0
Dec-15 | 15
您可以将月份列设置为索引。它看起来像 Excel 输入,如果是这样,它将在 2015 年 1 月 1 日被解析,因此您可以按如下方式重新采样:
df.set_index('Month').resample('MS').asfreq().fillna(0)
Out:
Count
Month
2015-01-01 10.0
2015-02-01 100.0
2015-03-01 20.0
2015-04-01 0.0
2015-05-01 0.0
2015-06-01 0.0
2015-07-01 10.0
2015-08-01 0.0
2015-09-01 11.0
2015-10-01 1.0
2015-11-01 0.0
2015-12-01 15.0
如果月份列不能识别为日期,需要先进行转换:
df['Month'] = pd.to_datetime(df['Month'], format='%b-%y')