Python Pandas – 在两个日期之间过滤 DataFrame
两个日期之间的过滤数据框,使用dataframe.loc。首先,导入所需的库-
import pandas as pd
创建带有日期记录的列表字典-
d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_Purchase': ['2021-07-10', '2021-08-12', '2021-06-17', '2021-03-16', '2021-02-19', '2021-08-22'] }
从上述列表字典创建数据框
dataFrame = pd.DataFrame(d)
获取在两个日期之间购买的汽车,即第一个日期:2021-05-10和第二个日期:2021-08-25-
resDF = dataFrame.loc[(dataFrame["Date_of_Purchase"] >= "2021-05-10") & (dataFrame["Date_of_Purchase"] <= "2021-08-25")]
示例
以下是代码-
import pandas as pd #列表字典 d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_Purchase': ['2021-07-10', '2021-08-12', '2021-06-17', '2021-03-16', '2021-02-19', '2021-08-22'] } #从上述列表字典创建数据框 dataFrame = pd.DataFrame(d) print"DataFrame...\n",dataFrame #获取在两个日期之间购买的汽车 #第一个日期:2021-05-10 #第二次日期:2021-08-25 resDF = dataFrame.loc[(dataFrame["Date_of_Purchase"] >= "2021-05-10") & (dataFrame["Date_of_Purchase"] <= "2021-08-25")] #打印过滤后的数据框 print"\nCars purchased between 2 dates: \n",resDF输出结果
这将产生以下输出-
DataFrame... Car Date_of_Purchase 0 BMW 2021-07-10 1 Lexus 2021-08-12 2 Audi 2021-06-17 3 Mercedes 2021-03-16 4 Jaguar 2021-02-19 5 Bentley 2021-08-22 Cars purchased between 2 dates: Car Date_of_Purchase 0 BMW 2021-07-10 1 Lexus 2021-08-12 2 Audi 2021-06-17 5 Bentley 2021-08-22