jen*_*nny 8 python dataframe pandas
所以我的代码如下:
df['Dates'][df['Dates'].index.month == 11]
Run Code Online (Sandbox Code Playgroud)
我正在做一个测试,看看我是否可以过滤几个月,所以它只显示11月的日期,但这不起作用.它给出了以下错误:AttributeError:'Int64Index'对象没有属性'month'.
如果我做
print type(df['Dates'][0])
Run Code Online (Sandbox Code Playgroud)
然后我得到类'pandas.tslib.Timestamp',这让我相信存储在数据帧中的对象类型是Timestamp对象.(我不确定"Int64Index"来自哪里......以前的错误)
我想要做的是:数据框列包含从2000年代早期到现在的日期格式:dd/mm/yyyy.我想仅在11月15日到3月15日期间过滤日期,与年份无关.最简单的方法是什么?
谢谢.
这是df ['Dates'](带索引):
0 2006-01-01
1 2006-01-02
2 2006-01-03
3 2006-01-04
4 2006-01-05
5 2006-01-06
6 2006-01-07
7 2006-01-08
8 2006-01-09
9 2006-01-10
10 2006-01-11
11 2006-01-12
12 2006-01-13
13 2006-01-14
14 2006-01-15
...
Run Code Online (Sandbox Code Playgroud)
Erf*_*fan 40
pd.to_datetime&dt访问器公认的答案不是解决这个问题的“熊猫”方式。要仅选择带有 的行month 11,请使用dt访问器:
# df['Date'] = pd.to_datetime(df['Date']) -- if column is not datetime yet
df = df[df['Date'].dt.month == 11]
Run Code Online (Sandbox Code Playgroud)
几天或几年都一样,你可以dt.month用dt.day或代替dt.year
除此之外,还有很多,这里有一些:
dt.quarterdt.weekdt.weekdaydt.day_namedt.is_month_enddt.is_month_startdt.is_year_enddt.is_year_start有关完整列表,请参阅文档
b10*_*10n 15
映射匿名函数以计算系列的月份,并将其与nov的11进行比较.这将给你一个布尔掩码.然后,您可以使用该掩码来过滤数据帧.
nov_mask = df['Dates'].map(lambda x: x.month) == 11
df[nov_mask]
Run Code Online (Sandbox Code Playgroud)
我认为没有直接的方式来过滤你想要忽略年份的方式所以试试这个.
nov_mar_series = pd.Series(pd.date_range("2013-11-15", "2014-03-15"))
#create timestamp without year
nov_mar_no_year = nov_mar_series.map(lambda x: x.strftime("%m-%d"))
#add a yearless timestamp to the dataframe
df["no_year"] = df['Date'].map(lambda x: x.strftime("%m-%d"))
no_year_mask = df['no_year'].isin(nov_mar_no_year)
df[no_year_mask]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14239 次 |
| 最近记录: |