如何在pandas中打印CSV中的某些行

时间:2018-05-11 13:38:51

标签: python python-3.x pandas csv datetime

我的问题是我有一个超过40000行的大数据帧,现在我想从2013-01-01 00:00:00到2013-31-12 00:00:00选择行

print(df.loc[df['localhour'] == '2013-01-01 00:00:00'])

现在我的代码,但我不能选择一个intervall打印出来......任何想法?

2 个答案:

答案 0 :(得分:1)

一种方法是将索引设置为datetime,然后将pd.DataFrame.loc与字符串索引器一起使用:

df = pd.DataFrame({'Date': ['2013-01-01', '2014-03-01', '2011-10-01', '2013-05-01'],
                   'Var': [1, 2, 3, 4]})

df['Date'] = pd.to_datetime(df['Date'])

res = df.set_index('Date').loc['2010-01-01':'2013-01-01']

print(res)

            Var
Date           
2013-01-01    1
2011-10-01    3

答案 1 :(得分:0)

创建一个datetime对象,然后应用条件:

print(df)

date
0   2013-01-01
1   2014-03-01
2   2011-10-01
3   2013-05-01

df['date']=pd.to_datetime(df['date'])
df['date'].loc[(df['date']<='2013-12-31 00:00:00') & (df['date']>='2013-01-01 00:00:00')]

输出:

0   2013-01-01
3   2013-05-01