熊猫在假期前添加天数

时间:2019-11-14 13:38:19

标签: python pandas

我需要添加一列“ next_holiday”,计算直到下一个假期的天数。添加列后,以下是预期的输出:

SalesDate holiday   next_holiday
2016-12-20  0             5
2016-12-21  0             4
2016-12-22  0             3
2016-12-23  0             2
2016-12-24  0             1
2016-12-25  1             0

2 个答案:

答案 0 :(得分:4)

这里有两行建议:

code=XXXX

答案 1 :(得分:1)

通过使用DataFrame的索引,可以避免使用groupby()

1。使用RangeIndex

假定以下数据框:

import pandas as pd

df = pd.DataFrame({
    'SalesDate': ['2016-12-20', '2016-12-21', '2016-12-22', '2016-12-23', '2016-12-24', '2016-12-25', '2016-12-26', '2016-12-27'],
    'holiday': [0, 0, 0, 0, 0, 1, 0, 0]
})

df

    SalesDate  holiday
0  2016-12-20        0
1  2016-12-21        0
2  2016-12-22        0
3  2016-12-23        0
4  2016-12-24        0
5  2016-12-25        1
6  2016-12-26        0
7  2016-12-27        0

单行解决方案:

如果DataFrame使用标准的RangeIndex,则可以使用df.index.where().bfill()df.index进行算术运算:

df['next_holiday'] = pd.Series(df.index.where(df.holiday == 1), dtype='Int32').fillna(method='bfill') - df.index  # Note: dtype'Int32' nullable int is new in pandas 0.24

结果:

df 
    SalesDate  holiday  next_holiday
0  2016-12-20        0             5
1  2016-12-21        0             4
2  2016-12-22        0             3
3  2016-12-23        0             2
4  2016-12-24        0             1
5  2016-12-25        1             0
6  2016-12-26        0           NaN
7  2016-12-27        0           NaN

2。使用DateTimeIndex

如果SalesDate是索引列(datetime64类型),则解决方案类似:

df = df.set_index(pd.to_datetime(df.SalesDate)).drop(columns=['SalesDate'])
df
            holiday
SalesDate          
2016-12-20        0
2016-12-21        0
2016-12-22        0
2016-12-23        0
2016-12-24        0
2016-12-25        1
2016-12-26        0
2016-12-27        0

日期计算解决方案:

df['next_holiday'] = ((pd.Series(df.index.where(df.holiday == 1)).fillna(method='bfill') - df.index) / np.timedelta64(1, 'D'))
df['next_holiday'] = df['next_holiday'].astype('Int32')  # pandas >= 0.24 for the nullable integer cast

结果:

df
            holiday  next_holiday
SalesDate                        
2016-12-20        0             5
2016-12-21        0             4
2016-12-22        0             3
2016-12-23        0             2
2016-12-24        0             1
2016-12-25        1             0
2016-12-26        0           NaN
2016-12-27        0           NaN
相关问题