按monthday Datafram筛选

2024-04-19 23:39:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想过滤几个月之间的熊猫数年的数据帧。你知道吗

我有一个包含2000-2016年数据的数据框,我想在每年的10月22日和11月15日之间进行过滤。你知道吗

为了保持简单,假设我有4列。日期指数、月份指数、日指数和价格。你知道吗

到目前为止,我尝试将month列和day列连接起来。10月22日变成1022年,11月15日变成1115年。你知道吗

当我看10点之前的日期时,问题就出现了。11月1日是111而不是1101。你知道吗

因此,当我执行指定df['monthday']>;1015&df['monthday']<;1115的条件筛选器时,它完全无法捕获从11月1日到11月9日的所有11月日期,因为从111到119<;1015。你知道吗

我还尝试将这个数字作为字符串进行比较,因此成功地将111转换为str(1101)。但这与int(1101)是不可比的。你知道吗

这是一个看起来很容易的问题,但我没有幸运地解决。感谢您的帮助。你知道吗

下面是代码段。谢谢你

df = web.DataReader('SPY', 'yahoo',datetime.datetime(2015 ,1, 1), 
datetime.datetime.today())

#this adds zeroes but really doesn't help me
df['Day of Month'] = df['Day of Month'].astype(str).str.zfill(2)
df['month'] = df['month'].astype(str).str.zfill(2)

#This one converts it to str but can't compare str to int
df['monthday'] = df['month'].map(str) + df['Day of Month'].map(str) 

#This one converts it to a # but can't use 111 as November 1st because it is 
#smaller than 1015 ie October 15th and I want to filter between those dates.
df['monthday'] = pd.to_numeric(df.monthday, errors='coerce')

#here is where I attempt my intermonth filter for each year since 2000
df = df[(df['month'] >= 10) & (df['month'] <= 11) & (df['monthday'] >= 1021)  
& (df['monthday'] <=1115)]

谢谢你的支持。你知道吗


Tags: ofto数据ltdfdatetimeit指数