根据最大值和最小值填写缺失的日期 pandas

Fill in missing dates pandas based off max and min

如何为条件

创建 python 语句

我有一个如下所示的数据框。我想知道如何根据数据框中的最大最小日期填写缺失的日期。

Day            Movie          Rating
2017-01-01     GreatGatsby    5
2017-01-02     TopGun         5
2017-01-03     Deadpool       1
2017-01-10     PlanetOfApes   2

我怎样才能将缺少的日期填充为类似

的内容
Day            Movie          Rating
2017-01-01     GreatGatsby    5
2017-01-02     TopGun         5
2017-01-03     Deadpool       1
2017-01-04     0              0
2017-01-05     0              0
2017-01-06     0              0
2017-01-07     0              0
2017-01-08     0              0
2017-01-09     0              0
2017-01-10     PlanetOfApes   2

我相信你需要reindex:

df = (df.set_index('Day')
       .reindex(pd.date_range(df['Day'].min(), df['Day'].max()), fill_value=0)
       .reset_index())

print (df)
       index         Movie  Rating
0 2017-01-01   GreatGatsby       5
1 2017-01-02        TopGun       5
2 2017-01-03      Deadpool       1
3 2017-01-04             0       0
4 2017-01-05             0       0
5 2017-01-06             0       0
6 2017-01-07             0       0
7 2017-01-08             0       0
8 2017-01-09             0       0
9 2017-01-10  PlanetOfApes       2

使用resample + first/last/min/max:

df.set_index('Day').resample('1D').first().fillna(0).reset_index()

         Day         Movie  Rating
0 2017-01-01   GreatGatsby     5.0
1 2017-01-02        TopGun     5.0
2 2017-01-03      Deadpool     1.0
3 2017-01-04             0     0.0
4 2017-01-05             0     0.0
5 2017-01-06             0     0.0
6 2017-01-07             0     0.0
7 2017-01-08             0     0.0
8 2017-01-09             0     0.0
9 2017-01-10  PlanetOfApes     2.0

如果 Day 不是 datetime 列,请先使用 pd.to_datetime 进行转换:

df['Day'] = pd.to_datetime(df['Day'])

文的另类 asfreq:

df.set_index('Day').asfreq('D').fillna(0).reset_index()

         Day         Movie  Rating
0 2017-01-01   GreatGatsby     5.0
1 2017-01-02        TopGun     5.0
2 2017-01-03      Deadpool     1.0
3 2017-01-04             0     0.0
4 2017-01-05             0     0.0
5 2017-01-06             0     0.0
6 2017-01-07             0     0.0
7 2017-01-08             0     0.0
8 2017-01-09             0     0.0
9 2017-01-10  PlanetOfApes     2.0