我有一个像这样的Pandas DataFrame:
╔════════════╦═══════╗ ║ DATE ║ VALUE ║ ╠════════════╬═══════╣ ║ 2011-01-07 ║ 1 ║ ╠════════════╬═══════╣ ║ 2011-01-08 ║ 2 ║ ╠════════════╬═══════╣ ║ 2011-01-09 ║ 1 ║ ╠════════════╬═══════╣ ║ 2011-01-10 ║ 1 ║ ╠════════════╬═══════╣ ║ 2011-01-20 ║ 1 ║ ╠════════════╬═══════╣ ║ 2011-01-20 ║ 1 ║ ╚════════════╩═══════╝
我现在要做的是从2011-01-20开始选择三天。通过df.loc['2011-01-20' - pd.Timedelta(3, unit='d'):'2011-01-20']
选择会产生以下日期框架:
╔════════════╦═══════╗ ║ DATE ║ VALUE ║ ╠════════════╬═══════╣ ║ 2011-01-20 ║ 1 ║ ╠════════════╬═══════╣ ║ 2011-01-20 ║ 1 ║ ╚════════════╩═══════╝
我想要完成的是以下数据框:
╔════════════╦═══════╗ ║ DATE ║ VALUE ║ ╠════════════╬═══════╣ ║ 2011-01-09 ║ 1 ║ ╠════════════╬═══════╣ ║ 2011-01-10 ║ 1 ║ ╠════════════╬═══════╣ ║ 2011-01-20 ║ 1 ║ ╠════════════╬═══════╣ ║ 2011-01-20 ║ 1 ║ ╚════════════╩═══════╝
我不想做的是groupby
或重新采样数据框或类似的东西,因为我需要保留结构以进行以下处理。有谁知道我怎么能解决这个问题?提前谢谢!
答案 0 :(得分:2)
您可以创建一个连续的id列,以便每个日期都有一个唯一ID,该ID随日期而增加,然后根据id列增加:
import pandas as pd
# sort the `DATE` column and create an id for each date
df['DATE'] = pd.to_datetime(df.DATE).sort_values()
df['DateId'] = df.groupby('DATE').grouper.group_info[0]
# find out the id for the target date
MaxId = df.DateId[df.DATE == '2011-01-20'].drop_duplicates().values
# subset based on the id column and the MaxId
df.loc[df.DateId.isin(range(MaxId - 2, MaxId + 1)),['DATE', 'VALUE']]
# DATE VALUE
# 2 2011-01-09 1
# 3 2011-01-10 1
# 4 2011-01-20 1
# 5 2011-01-20 1
答案 1 :(得分:0)
使用pandas.ix尝试此操作
提示:df.ix(start, stop)
df['Date'] =pd.to_datetime(df['Date']).sort_values()
df.ix[df[df.Date =='2011-01-20'].index[0]-2: max(df[df.Date =='2011-01-20'].index)]
Date Value
2 2011-01-09 1
3 2011-01-10 1
4 2011-01-20 1
5 2011-01-20 1
6 2011-01-20 1