【问题标题】:Filter by monthday Pandas Dataframe按月份筛选 Pandas 数据框
【发布时间】:2017-10-23 02:46:24
【问题描述】:

我想在几个月之间过滤熊猫数据框多年。

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

为了简单起见,假设我有 4 列。日期索引、月份索引、日期索引和价格。

到目前为止,我尝试的是连接月份列和日期列。 IE。 10 月 22 日变为 1022,11 月 15 日变为 1115。

当我查看 #10 之前的日期时,问题就出现了。 IE。 11 月 1 日是 111 而不是 1101。

因此,当我执行指定 df['monthday'] > 1015 & df['monthday']

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

这是一个看似简单的问题,但我没能解决。任何帮助表示赞赏。

下面的代码 sn-ps。谢谢,

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)]

感谢您的支持。

【问题讨论】:

  • 如果大小为
  • 我已按照以下代码附加:df['Day of Month'] = df['Day of Month'].astype(str).str.zfill(2)。但是我无法将 str 与 int 进行比较。
  • 您仍然可以比较字符串数字...按字典顺序,因此将所有内容转换为字符串并进行比较。
  • 更新了代码以反映我在代码中添加 0 的位置。
  • 感谢您提供更多详细信息,这将非常有帮助

标签: python pandas dataframe filter filtering


【解决方案1】:
dfperiod = df[(df['month'] >= '10') & (df['month'] <= '11') & (df['monthday'] 
>= '1021')  & (df['monthday'] <='1115')]

【讨论】:

    猜你喜欢
    • 2018-06-11
    • 2014-11-26
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    相关资源
    最近更新 更多