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

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

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


当前回答

你可以使用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

其他回答

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

我宁愿不改变df。

一个选项是检索开始和结束日期的索引:

import numpy as np   
import pandas as pd

#Dummy DataFrame
df = pd.DataFrame(np.random.random((30, 3)))
df['date'] = pd.date_range('2017-1-1', periods=30, freq='D')

#Get the index of the start and end dates respectively
start = df[df['date']=='2017-01-07'].index[0]
end = df[df['date']=='2017-01-14'].index[0]

#Show the sliced df (from 2017-01-07 to 2017-01-14)
df.loc[start:end]

结果是:

     0   1   2       date
6  0.5 0.8 0.8 2017-01-07
7  0.0 0.7 0.3 2017-01-08
8  0.8 0.9 0.0 2017-01-09
9  0.0 0.2 1.0 2017-01-10
10 0.6 0.1 0.9 2017-01-11
11 0.5 0.3 0.9 2017-01-12
12 0.5 0.4 0.3 2017-01-13
13 0.4 0.9 0.9 2017-01-14

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

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

这对我很管用。

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