我正在从csv创建一个DataFrame,如下所示:

stock = pd.read_csv('data_in/' + filename + '.csv', skipinitialspace=True)

DataFrame有一个日期列。是否有一种方法可以创建一个新的DataFrame(或者只是覆盖现有的DataFrame),它只包含日期值落在指定日期范围内或两个指定日期值之间的行?


当前回答

我觉得最好的选择是使用直接检查,而不是使用loc函数:

df = df[(df['date'] > '2000-6-1') & (df['date'] <= '2000-6-10')]

这对我很管用。

使用切片的loc函数的主要问题是限制应该出现在实际值中,否则将导致KeyError。

其他回答

强烈建议将日期列转换为索引。这样做会提供很多便利。一个是很容易选择两个日期之间的行,你可以看到这个例子:

import numpy as np   
import pandas as pd

# Dataframe with monthly data between 2016 - 2020
df = pd.DataFrame(np.random.random((60, 3)))
df['date'] = pd.date_range('2016-1-1', periods=60, freq='M')

如果要选择2017-01-01到2019-01-01之间的行,只需将日期列转换为索引:

df.set_index('date', inplace=True)

然后是切片:

df.loc['2017':'2019']

你可以在直接读取csv文件时选择date列作为索引,而不是df.set_index():

df = pd.read_csv('file_name.csv',index_col='date') 

你可以使用truncate方法:

dates = pd.date_range('2016-01-01', '2016-01-06', freq='d')
df = pd.DataFrame(index=dates, data={'A': 1})

            A
2016-01-01  1
2016-01-02  1
2016-01-03  1
2016-01-04  1
2016-01-05  1
2016-01-06  1

选择两个日期之间的数据:

df.truncate(before=pd.Timestamp('2016-01-02'),
            after=pd.Timestamp('2016-01-4'))

输出:

            A
2016-01-02  1
2016-01-03  1
2016-01-04  1

灵感来自unutbu

print(df.dtypes)                                 #Make sure the format is 'object'. Rerunning this after index will not show values.
columnName = 'YourColumnName'
df[columnName+'index'] = df[columnName]          #Create a new column for index
df.set_index(columnName+'index', inplace=True)   #To build index on the timestamp/dates
df.loc['2020-09-03 01:00':'2020-09-06']          #Select range from the index. This is your new Dataframe.

你也可以用between:

df[df.some_date.between(start_date, end_date)]

我觉得最好的选择是使用直接检查,而不是使用loc函数:

df = df[(df['date'] > '2000-6-1') & (df['date'] <= '2000-6-10')]

这对我很管用。

使用切片的loc函数的主要问题是限制应该出现在实际值中,否则将导致KeyError。