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

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

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


当前回答

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)

其他回答

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

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

你也可以用between:

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