我需要添加一列“ 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
答案 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