gpt4 book ai didi

Python pandas 数据帧 : filtering around key dates

转载 作者:太空宇宙 更新时间:2023-11-03 15:07:37 26 4
gpt4 key购买 nike

我有一个 pandas 日期框架 df,其索引是每日 DatetimeIndex,以及一个带有 historical_sales 的附加列。

如果我们想过滤过去历史销售量大于较大数字(例如 200)的日子,很简单:

df.loc[df['historical_sales'>200]]

但是,我想知道,如果我们想探索销售额 > 200 的前后 5 天的销售模式该怎么办?

非常感谢。

最佳答案

我认为您需要通过列表理解获取所有索引值,然后通过loc进行选择.

也是必要的使用numpy.concatenate用于将所有索引连接在一起 numpy.unique用于删除重复项。

np.random.seed(100)
rng = pd.date_range('2017-04-03', periods=20)
df = pd.DataFrame({'historical_sales': np.random.choice([100,200,300], size=20)}, index=rng)
print (df)
historical_sales
2017-04-03 100
2017-04-04 100
2017-04-05 100
2017-04-06 300
2017-04-07 300
2017-04-08 100
2017-04-09 300
2017-04-10 200
2017-04-11 300
2017-04-12 300
2017-04-13 300
2017-04-14 300
2017-04-15 200
2017-04-16 100
2017-04-17 100
2017-04-18 100
2017-04-19 100
2017-04-20 300
2017-04-21 100
2017-04-22 200
<小时/>
idxmask = df.index[df['historical_sales']>200]
print (idxmask)
DatetimeIndex(['2017-04-06', '2017-04-07', '2017-04-09', '2017-04-11',
'2017-04-12', '2017-04-13', '2017-04-14', '2017-04-20'],
dtype='datetime64[ns]', freq=None)

#in real data change 1 to 5 for 5 days
temp_index = [df.loc[timestamp - pd.Timedelta(1, unit='d') :
timestamp + pd.Timedelta(1, unit='d')].index for timestamp in idxmask]
idx = np.unique(np.concatenate(temp_index))

df1 = df.loc[idx]
print (df1)
historical_sales
2017-04-05 100
2017-04-06 300
2017-04-07 300
2017-04-08 100
2017-04-09 300
2017-04-10 200
2017-04-11 300
2017-04-12 300
2017-04-13 300
2017-04-14 300
2017-04-15 200
2017-04-19 100
2017-04-20 300
2017-04-21 100

关于Python pandas 数据帧 : filtering around key dates,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44512741/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com