简体   繁体   中英

Extract data of last 5 days

I need help here, I am trying to extract the data of last 5 days, but I always end up with an error.

Data

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

Code

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

df = df['Data_Date']

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

Error

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'>

If need last 5 days before today use Series.between in boolean indexing :

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

Or if don need inclusive filter ( > and < ):

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

But if need compare for > or >= change mask to:

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

df = df[mask]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM