按日期索引在数据框中筛选行

3
我希望能按日期过滤以下数据框,只想要根据索引值中的星期三进行过滤:
begin=2015-05-14
end=2015-05-22

Date
2015-05-14   81.370003  6.11282  39.753  44.950001
2015-05-15   80.419998  6.03380  39.289  44.750000
2015-05-18   80.879997  6.00746  41.249  44.360001
2015-05-19   80.629997  6.10465  41.047  40.980000
2015-05-20   80.550003  6.14370  41.636  42.790001
2015-05-21   80.480003  6.16096  42.137  43.680000
2015-05-22   80.540001  6.13916  42.179  43.490002

这是我尝试过的内容:

并且继续下去...

df1=df[df.index.dayofweek == 2]

然后尝试:

df.index = pd.date_range(begin,end,freq='W')

两种情况都没有成功。

期望的输出是相同的数据框,只返回星期三的行。


对我来说,df1=df[df.index.dayofweek == 2]有效,有什么问题吗? - jezrael
你不需要知道哪些日期是星期三吗?或者Pandas有一个内置的日历它会检查吗? - Chuck
@jezrael 不知道为什么会出现'Panel'对象没有属性'index'的错误。 - JamesHudson81
嗯,可能存在问题,你的数据在“Panel”中,而不是“DataFrame”中。你是如何创建它的? - jezrael
使用Pandas Datareader导入数据。 - JamesHudson81
2个回答

6

看起来你需要先进行过滤:

df = df.loc[begin:end]
df1=df[df.index.dayofweek == 2]
print (df1)
                    a       b       c          d
2015-05-20  80.550003  6.1437  41.636  42.790001

1

这不是最优雅的解决方案,可能远离Pythonic。但它能解决问题。(在运行之前将所有数据放入Pandas数据框中)

import datetime
import pandas as pd
import time
import calendar
b=0
for date in a:
    x = time.strptime(date, "%Y-%m-%d") #strips date in to its components
    year=x.tm_year #get year this is necessary for the way datetime.date works (to my best understanding)
    month=x.tm_mon #get month
    day=x.tm_mday #get day
    dayofweek=datetime.date(year,month,day).weekday() #use above to determine day of the week
    if dayofweek is 2:    
        df.set_value(b, 'col6', True) #create extra column that is True if day of week is Wednesday
    b=b+1
df=df.loc[df['col6'] == True] #drop everything in df that is not a Wednesday observation

Jezreal的解决方案似乎更简单、更符合Python风格。我为自己在网站上第一次成功解决问题感到非常自豪,所以暂时不会撤回我的解决方案。 - Peter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接