我正在从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。

其他回答

另一种方法是使用pandas.DataFrame.query()方法。让我给你们看一个关于下面数据帧的例子,叫做df。

>>> df = pd.DataFrame(np.random.random((5, 1)), columns=['col_1'])
>>> df['date'] = pd.date_range('2020-1-1', periods=5, freq='D')
>>> print(df)
      col_1       date
0  0.015198 2020-01-01
1  0.638600 2020-01-02
2  0.348485 2020-01-03
3  0.247583 2020-01-04
4  0.581835 2020-01-05

作为参数,使用条件进行过滤,如下所示:

>>> start_date, end_date = '2020-01-02', '2020-01-04'
>>> print(df.query('date >= @start_date and date <= @end_date'))
      col_1       date
1  0.244104 2020-01-02
2  0.374775 2020-01-03
3  0.510053 2020-01-04

如果你不想包含边界,只需要像下面这样改变条件:

>>> print(df.query('date > @start_date and date < @end_date'))
      col_1       date
2  0.374775 2020-01-03

您可以像这样在日期列上使用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

你可以用pd.date_range()和Timestamp来做。 假设你已经使用parse_dates选项读取了一个带日期列的csv文件:

df = pd.read_csv('my_file.csv', parse_dates=['my_date_col'])

然后你可以定义一个日期范围索引:

rge = pd.date_range(end='15/6/2020', periods=2)

然后通过地图根据日期过滤你的值:

df.loc[df['my_date_col'].map(lambda row: row.date() in rge)]

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

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

这对我很管用。

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

import pandas as pd

technologies = ({
    'Courses':["Spark","PySpark","Hadoop","Python","Pandas","Hadoop","Spark"],
    'Fee' :[22000,25000,23000,24000,26000,25000,25000],
    'Duration':['30days','50days','55days','40days','60days','35days','55days'],
    'Discount':[1000,2300,1000,1200,2500,1300,1400],
    'InsertedDates':["2021-11-14","2021-11-15","2021-11-16","2021-11-17","2021-11-18","2021-11-19","2021-11-20"]
               })
df = pd.DataFrame(technologies)
print(df)

使用pandas.DataFrame.loc按日期过滤行

方法1:

    mask = (df['InsertedDates'] > start_date) & (df['InsertedDates'] <= end_date)

    df2 = df.loc[mask]
    print(df2)

方法2:

    start_date = '2021-11-15'
    end_date = '2021-11-19'
    after_start_date = df["InsertedDates"] >= start_date
    before_end_date = df["InsertedDates"] <= end_date
    between_two_dates = after_start_date & before_end_date


    df2 = df.loc[between_two_dates]
    print(df2)

使用pandas.DataFrame.query()选择数据帧行

start_date = '2021-11-15'
end_date   = '2021-11-18'
df2 = df.query('InsertedDates >= @start_date and InsertedDates <= @end_date')
print(df2)

使用datafframe .query()选择两个日期之间的行

start_date = '2021-11-15'
end_date = '2021-11-18'
df2 = df.query('InsertedDates > @start_date and InsertedDates < @end_date')
print(df2)

pandas.Series.between()函数使用两个日期

df2 = df.loc[df["InsertedDates"].between("2021-11-16", "2021-11-18")]
print(df2)

使用DataFrame.isin()在两个日期之间选择数据帧行

df2 = df[df["InsertedDates"].isin(pd.date_range("2021-11-15", "2021-11-17"))]
print(df2)