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

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

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


当前回答

您可以像这样在日期列上使用isin方法 df (df .isin (pd(“日期”)。date_range (start_date end_date)))

注意:这只适用于日期(正如问题所要求的),而不适用于时间戳。

例子:

import numpy as np   
import pandas as pd

# Make a DataFrame with dates and random numbers
df = pd.DataFrame(np.random.random((30, 3)))
df['date'] = pd.date_range('2017-1-1', periods=30, freq='D')

# Select the rows between two dates
in_range_df = df[df["date"].isin(pd.date_range("2017-01-15", "2017-01-20"))]

print(in_range_df)  # print result

这给了

           0         1         2       date
14  0.960974  0.144271  0.839593 2017-01-15
15  0.814376  0.723757  0.047840 2017-01-16
16  0.911854  0.123130  0.120995 2017-01-17
17  0.505804  0.416935  0.928514 2017-01-18
18  0.204869  0.708258  0.170792 2017-01-19
19  0.014389  0.214510  0.045201 2017-01-20

其他回答

为了保持解决方案的简单和python性,我建议您尝试一下。

在这种情况下,如果你要经常这样做,最好的解决方案是首先将日期列设置为索引,这将转换DateTimeIndex中的列,并使用以下条件切片任何范围的日期。

import pandas as pd

data_frame = data_frame.set_index('date')

df = data_frame[(data_frame.index > '2017-08-10') & (data_frame.index <= '2017-08-15')]

你也可以用between:

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

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

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') 

您可以像这样在日期列上使用isin方法 df (df .isin (pd(“日期”)。date_range (start_date end_date)))

注意:这只适用于日期(正如问题所要求的),而不适用于时间戳。

例子:

import numpy as np   
import pandas as pd

# Make a DataFrame with dates and random numbers
df = pd.DataFrame(np.random.random((30, 3)))
df['date'] = pd.date_range('2017-1-1', periods=30, freq='D')

# Select the rows between two dates
in_range_df = df[df["date"].isin(pd.date_range("2017-01-15", "2017-01-20"))]

print(in_range_df)  # print result

这给了

           0         1         2       date
14  0.960974  0.144271  0.839593 2017-01-15
15  0.814376  0.723757  0.047840 2017-01-16
16  0.911854  0.123130  0.120995 2017-01-17
17  0.505804  0.416935  0.928514 2017-01-18
18  0.204869  0.708258  0.170792 2017-01-19
19  0.014389  0.214510  0.045201 2017-01-20

灵感来自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.