簡體   English   中英

提取最近 5 天的數據

[英]Extract data of last 5 days

我在這里需要幫助,我正在嘗試提取最近 5 天的數據,但我總是以錯誤告終。

數據

Data_Date     A
2021-03-11  1145942
2021-03-12  1105853
2021-03-13  2101335
2021-03-14  1640319
2021-03-15  1584698
2021-03-16  1516285
2021-03-17  2822152
2021-03-18  2186634
2021-03-19  1136144

代碼

today = pd.datetime.today().date()

df = df['Data_Date']

df['Data_Date'] = df[today - pd.offsets.Day(5):]

錯誤

TypeError: cannot do slice indexing on <class 'pandas.core.indexes.range.RangeIndex'> with these indexers [2021-03-17 00:00:00] of <class 'pandas._libs.tslibs.timestamps.Timestamp'>

如果需要在今天之前的最后 5 天使用Series.between boolean indexing中的 Series.between :

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

today = pd.to_datetime('today').normalize()

mask = df['Data_Date'].between(today - pd.offsets.Day(5), today)

df = df[mask]
print (df)
   Data_Date        A
6 2021-03-17  2822152
7 2021-03-18  2186634
8 2021-03-19  1136144

或者如果不需要包含過濾器( >< ):

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

today = pd.to_datetime('today').normalize()

mask = df['Data_Date'].between(today - pd.offsets.Day(5), today, inclusive=False)

df = df[mask]
print (df)
   Data_Date        A
7 2021-03-18  2186634
8 2021-03-19  1136144

但如果需要比較>>=將掩碼更改為:

mask = df['Data_Date'] > today - pd.offsets.Day(5)
mask = df['Data_Date'] >= today - pd.offsets.Day(5)

df = df[mask]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM