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-05-19', '2021-08-22'] }
使用上述列表字典创建一个 DataFrame −
dataFrame = pd.DataFrame(d)
现在,假设我们需要获取在某一特定日期后购买的汽车。为此,我们使用 loc −
resDF = dataFrame.loc[dataFrame["Date_of_Purchase"] > "2021-07-15"]
範例
以下为完整代码 −
import pandas as pd # dictionary of lists d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_Purchase': ['2021-07-10', '2021-08-12', '2021-06-17', '2021-03-16', '2021-05-19', '2021-08-22'] } # creating dataframe from the above dictionary of lists dataFrame = pd.DataFrame(d) print"DataFrame...\n",dataFrame # fetch cars purchased after 15th July 2021 resDF = dataFrame.loc[dataFrame["Date_of_Purchase"] > "2021-07-15"] # print filtered data frame print"\nCars purchased after 15th July 2021: \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-05-19 5 Bentley 2021-08-22 Cars purchased after 15th July 2021: Car Date_of_Purchase 1 Lexus 2021-08-12 5 Bentley 2021-08-22
广告