Python 切片数据帧
考虑数据帧Python 切片数据帧,python,pandas,Python,Pandas,考虑数据帧数据: one two three four Ohio 2013-01-01 1 2 3 Colorado 2014-01-05 5 6 7 Utah 2015-05-06 9 10 11 New York 2016-10-11 13 14 15 我希望仅使用该年为给定年份的标准来提取行,例如,类似于数据['one'][:][0:4]=
数据:
one two three four
Ohio 2013-01-01 1 2 3
Colorado 2014-01-05 5 6 7
Utah 2015-05-06 9 10 11
New York 2016-10-11 13 14 15
我希望仅使用该年为给定年份的标准来提取行,例如,类似于数据['one'][:][0:4]=='2013'
。但是命令data['one'][:][0:4]
返回
Ohio 2013-01-01
Colorado 2014-01-05
Utah 2015-05-06
New York 2016-10-11
Name: one, dtype: object
'2013'
我认为这样做是正确的,因为命令data['one'][0][0:4]
返回
Ohio 2013-01-01
Colorado 2014-01-05
Utah 2015-05-06
New York 2016-10-11
Name: one, dtype: object
'2013'
为什么会有差异?正确的方法是什么?您要寻找的条件是
df['one'].str[0:4] == "2013"
基本上,您需要告诉Pandas将列作为字符串读取,然后对该列中的字符串进行操作
你写它的方式(df['one'][:]
)说“给我一个名为“one”的列,然后给我所有的[:]
因为列'one'
由日期组成,最好让熊猫识别它,而不是将它识别为字符串。你可以使用pd.to\u datetime
来实现这一点:
df['one'] = pd.to_datetime(df['one'])
这使您可以根据日期属性进行筛选,而无需担心对字符串进行切片。例如,您可以使用Series.dt.year
检查年份:
df['one'].dt.year == 2013
将其与loc
相结合,可以获得2013年的所有行:
df.loc[df['one'].dt.year == 2013, :]
query
在datetime列上也很有效
In [13]: df.query('one == 2013')
Out[13]:
one two three four
Ohio 2013-01-01 1 2 3
我相信他想要整排人