2024-09-30 12:30:27 发布
网友
我需要添加一个列“下一个假日”计算天到下一个假日。以下是添加列后的预期输出:
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
这里有两条建议:
temp = df.holiday.iloc[::-1].eq(1).cumsum() df['next_holiday'] = temp.groupby(temp).cumcount()
通过使用数据帧的索引,可以避免groupby()。你知道吗
groupby()
<强>1。使用范围索引
假设以下数据帧:
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
单线解决方案:
如果数据帧使用标准RangeIndex,则可以使用df.index.where().bfill()和df.index进行算术运算:
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类型),则解决方案类似:
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
这里有两条建议:
通过使用数据帧的索引,可以避免
groupby()
。你知道吗<强>1。使用范围索引
假设以下数据帧:
单线解决方案:
如果数据帧使用标准RangeIndex,则可以使用
df.index.where().bfill()
和df.index
进行算术运算:结果:
<强>2。使用DateTimeIndex
如果
SalesDate
是索引列(datetime64
类型),则解决方案类似:用日期算法求解:
结果:
相关问题 更多 >
编程相关推荐