我有一个熊猫DataFrame与“日期”列。现在我需要过滤掉DataFrame中日期在未来两个月之外的所有行。实际上,我只需要保留接下来两个月内的行。
实现这一目标的最佳方式是什么?
我有一个熊猫DataFrame与“日期”列。现在我需要过滤掉DataFrame中日期在未来两个月之外的所有行。实际上,我只需要保留接下来两个月内的行。
实现这一目标的最佳方式是什么?
当前回答
你可以通过这样做来选择时间范围:df.loc['start_date':'end_date']
其他回答
用pyjanitor怎么样
它有很酷的功能。
pip后安装pyjanitor
import janitor
df_filtered = df.filter_date(your_date_column_name, start_date, end_date)
按日期过滤数据帧的最短方法: 假设你的日期列的类型是datetime64[ns]
# filter by single day
df_filtered = df[df['date'].dt.strftime('%Y-%m-%d') == '2014-01-01']
# filter by single month
df_filtered = df[df['date'].dt.strftime('%Y-%m') == '2014-01']
# filter by single year
df_filtered = df[df['date'].dt.strftime('%Y') == '2014']
我还不允许写评论,所以我会写一个答案,如果有人读了所有的评论,并找到了这个。
如果数据集的索引是一个日期时间,并且您想仅通过(例如)月份过滤它,您可以执行以下操作:
df.loc[df.index.month == 3]
它将在3月份为您过滤数据集。
如果您已经使用pd将字符串转换为日期格式。To_datetime你可以使用:
df = df [(df[日期]>”2018-01-01”)及(df[日期]<”2019-07-01”)
因此,在加载csv数据文件时,我们需要将日期列设置为索引,如下所示,以便根据日期范围筛选数据。现在已弃用的方法:pd.DataFrame.from_csv()不需要这样做。
如果您只想显示1月至2月两个月的数据,例如2020-01-01至2020-02-29,您可以这样做:
import pandas as pd
mydata = pd.read_csv('mydata.csv',index_col='date') # or its index number, e.g. index_col=[0]
mydata['2020-01-01':'2020-02-29'] # will pull all the columns
#if just need one column, e.g. Cost, can be done:
mydata['2020-01-01':'2020-02-29','Cost']
这已经在Python 3.7中进行了测试。希望这对你有用。