python中按日期和时间对数据帧进行索引和切片
我有时间序列数据集。我可以通过此代码选择3月至5月的数据:python中按日期和时间对数据帧进行索引和切片,python,pandas,numpy,dataframe,Python,Pandas,Numpy,Dataframe,我有时间序列数据集。我可以通过此代码选择3月至5月的数据: df[(df.index.month >=3) & (df.index.month<=5)] 您可以使用helper系列s将所有年份替换为相同年份-例如2000: print (df) A 2001-02-25 0.01 2002-02-26 0.03 2003-02-27 1.00 2004-02-28 1.52 2005-03-29 0.23 2006-03-01 0.
df[(df.index.month >=3) & (df.index.month<=5)]
您可以使用helper
系列
s
将所有年份替换为相同年份-例如2000
:
print (df)
A
2001-02-25 0.01
2002-02-26 0.03
2003-02-27 1.00
2004-02-28 1.52
2005-03-29 0.23
2006-03-01 0.45
2007-03-05 2.15
2008-03-06 1.75
s = pd.Series(df.index.map(lambda x: pd.datetime(2000, x.month, x.day)))
mask = (s.dt.date > pd.datetime(2000,3,15).date()) &
(s.dt.date < pd.datetime(2000,5,15).date())
mask.index = df.index
print (mask)
2001-02-25 False
2002-02-26 False
2003-02-27 False
2004-02-28 False
2005-03-29 True
2006-03-01 False
2007-03-05 False
2008-03-06 False
dtype: bool
df = df[mask]
print (df)
A
2005-03-29 0.23
打印(df)
A.
2001-02-25 0.01
2002-02-26 0.03
2003-02-27 1.00
2004-02-28 1.52
2005-03-29 0.23
2006-03-01 0.45
2007-03-05 2.15
2008-03-06 1.75
s=pd.Series(df.index.map(lambda x:pd.datetime(2000,x.month,x.day)))
掩码=(s.dt.date>pd.datetime(2000,3,15).date())和
(s.dt.date
15代表日还是年?15不是年,所以您希望所有年份的数据都是从3月15日到5月15日,而不是一年?准确地说。我正在寻找所有年份3月15日至5月15日的数据。请参阅
print (df)
A
2001-02-25 0.01
2002-02-26 0.03
2003-02-27 1.00
2004-02-28 1.52
2005-03-29 0.23
2006-03-01 0.45
2007-03-05 2.15
2008-03-06 1.75
s = pd.Series(df.index.map(lambda x: pd.datetime(2000, x.month, x.day)))
mask = (s.dt.date > pd.datetime(2000,3,15).date()) &
(s.dt.date < pd.datetime(2000,5,15).date())
mask.index = df.index
print (mask)
2001-02-25 False
2002-02-26 False
2003-02-27 False
2004-02-28 False
2005-03-29 True
2006-03-01 False
2007-03-05 False
2008-03-06 False
dtype: bool
df = df[mask]
print (df)
A
2005-03-29 0.23