[英]Fill missing dates in a pandas DataFrame
I've a lot of DataFrames with 2 columns, like this:我有很多带有 2 列的 DataFrame,如下所示:
Fecha费查 | unidades独联体 | |
---|---|---|
0 0 | 2020-01-01 2020-01-01 | 2.0 2.0 |
84048 84048 | 2020-09-01 2020-09-01 | 4.0 4.0 |
149445 149445 | 2020-10-01 2020-10-01 | 11.0 11.0 |
532541 532541 | 2020-11-01 2020-11-01 | 4.0 4.0 |
660659 660659 | 2020-12-01 2020-12-01 | 2.0 2.0 |
1515682 1515682 | 2021-03-01 2021-03-01 | 9.0 9.0 |
1563644 1563644 | 2021-04-01 2021-04-01 | 2.0 2.0 |
1759823 1759823 | 2021-05-01 2021-05-01 | 1.0 1.0 |
2226586 2226586 | 2021-07-01 2021-07-01 | 1.0 1.0 |
As it can be seen, there are some months that are missing.可以看出,缺少一些月份。 Missing data depends on the DataFrame, I can have 2 months, 10, 100% complete, only one...I need to complete column "Fecha" with missing months (from 2020-01-01 to 2021-12-01) and when date is added into "Fecha", add "0" value to "unidades" column.缺失数据取决于 DataFrame,我可以有 2 个月,10,100% 完成,只有一个......我需要填写缺失月份的“Fecha”列(从 2020-01-01 到 2021-12-01)和将日期添加到“Fecha”时,将“0”值添加到“unidades”列。
Each element in Fecha Column is a class 'pandas._libs.tslibs.timestamps.Timestamp Fecha Column 中的每个元素都是一个 class 'pandas._libs.tslibs.timestamps.Timestamp
How could I fill the missing dates for each DataFrame??如何填写每个 DataFrame 的缺失日期?
You could create a date range and use "Fecha" column to set_index
+ reindex
to add missing months.您可以创建一个日期范围并使用“Fecha”列来set_index
+ reindex
添加缺失的月份。 Then fillna
+ reset_index
fetches the desired outcome:然后fillna
+ reset_index
获取所需的结果:
df['Fecha'] = pd.to_datetime(df['Fecha'])
df = (df.set_index('Fecha')
.reindex(pd.date_range('2020-01-01', '2021-12-01', freq='MS'))
.rename_axis(['Fecha'])
.fillna(0)
.reset_index())
Output: Output:
Fecha unidades
0 2020-01-01 2.0
1 2020-02-01 0.0
2 2020-03-01 0.0
3 2020-04-01 0.0
4 2020-05-01 0.0
5 2020-06-01 0.0
6 2020-07-01 0.0
7 2020-08-01 0.0
8 2020-09-01 4.0
9 2020-10-01 11.0
10 2020-11-01 4.0
11 2020-12-01 2.0
12 2021-01-01 0.0
13 2021-02-01 0.0
14 2021-03-01 9.0
15 2021-04-01 2.0
16 2021-05-01 1.0
17 2021-06-01 0.0
18 2021-07-01 1.0
19 2021-08-01 0.0
20 2021-09-01 0.0
21 2021-10-01 0.0
22 2021-11-01 0.0
23 2021-12-01 0.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.