在日期过滤Pandas DataFrames

AMM*_*AMM 117 python datetime filtering dataframe pandas

我有一个带有"日期"列的Pandas DataFrame.现在我需要过滤掉DataFrame中具有接下来两个月之外的日期的所有行.基本上,我只需要保留未来两个月内的行.

实现这一目标的最佳方法是什么?

Ret*_*ozi 191

如果date列是索引,则使用.loc进行基于标签的索引,或使用.iloc进行位置索引.

例如:

df.loc['2014-01-01':'2014-02-01']
Run Code Online (Sandbox Code Playgroud)

详情请见http://pandas.pydata.org/pandas-docs/stable/dsintro.html#indexing-selection

如果列不是索引,则有两个选择:

  1. 将其作为索引(如果是时间序列数据,则暂时或永久)
  2. df[(df['date'] > '2013-01-01') & (df['date'] < '2013-02-01')]

请参阅此处以获取一般说明

注意:.ix已弃用.

  • 你也可以在这里使用`query`.`df.query('20130101 <date <20130201')`. (33认同)
  • 您应该提到索引的过滤器(通过`.loc`和`.ix`)和示例中的列不等效.`df.ix ['2014-01-01':'2014-02-01']`包括`2014-02-01`而``df [(df ['date']>'2013-01-01') &(df ['date'] <'2013-02-01')]`不包括`2013-02-01`,它只会匹配到2013-01-31`的行. (7认同)
  • 如果不想过滤某个日期范围,而是多个日期时间该怎么办? (4认同)
  • 此调用现已弃用! (3认同)
  • 谢谢,会读。日期是一个单独的列,而不是我的情况下的索引。我可能应该首先提供这些信息。我的问题不是很有益。 (2认同)
  • 与:http://stackoverflow.com/questions/16341367/grabbing-selection- Between-specific-dates-in-a-dataframe 这也很有用。 (2认同)

ora*_*ge1 36

以前的答案在我的经验中是不正确的,你不能传递一个简单的字符串,需要是一个datetime对象.所以:

import datetime 
df.loc[datetime.date(year=2014,month=1,day=1):datetime.date(year=2014,month=2,day=1)]
Run Code Online (Sandbox Code Playgroud)

  • 我绝对可以传递一个没有问题的字符串. (8认同)
  • 不推荐使用ix索引器,使用loc - http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated (8认同)
  • 我使用这个收到以下错误:TypeError:'int'和'datetime.date'实例之间不支持'<' (6认同)
  • 熊猫会将任何“日期时间”字符串转换为日期时间对象..所以它是正确的 (3认同)

shm*_*008 31

如果您的日期通过导入日期时间包标准化,您可以简单地使用:

df[(df['date']>datetime.date(2016,1,1)) & (df['date']<datetime.date(2016,3,1))]  
Run Code Online (Sandbox Code Playgroud)

要使用datetime包标记日期字符串,可以使用此功能:

import datetime
datetime.datetime.strptime
Run Code Online (Sandbox Code Playgroud)

  • 建议使用 df[(df['date']&gt;pd.Timestamp(2016,1,1)) &amp; (df['date']&lt;pd.Timestamp(2016,3,1))]`。 (11认同)

小智 28

如果您已经使用 pd.to_datetime 将字符串转换为日期格式,则可以使用:

df = df[(df['Date']> "2018-01-01") & (df['Date']< "2019-07-01")]


VMA*_*Atm 15

如果您的datetime列具有Pandas日期时间类型(例如datetime64[ns]),为了正确过滤,您需要pd.Timestamp对象,例如:

from datetime import date

import pandas as pd

value_to_check = pd.Timestamp(date.today().year, 1, 1)
filter_mask = df['date_column'] < value_to_check
filtered_df = df[filter_mask]
Run Code Online (Sandbox Code Playgroud)


dan*_*sca 12

您可以使用 pd.Timestamp 来执行查询和本地引用

import pandas as pd
import numpy as np

df = pd.DataFrame()
ts = pd.Timestamp

df['date'] = np.array(np.arange(10) + datetime.now().timestamp(), dtype='M8[s]')

print(df)
print(df.query('date > @ts("20190515T071320")')
Run Code Online (Sandbox Code Playgroud)

与输出

                 date
0 2019-05-15 07:13:16
1 2019-05-15 07:13:17
2 2019-05-15 07:13:18
3 2019-05-15 07:13:19
4 2019-05-15 07:13:20
5 2019-05-15 07:13:21
6 2019-05-15 07:13:22
7 2019-05-15 07:13:23
8 2019-05-15 07:13:24
9 2019-05-15 07:13:25


                 date
5 2019-05-15 07:13:21
6 2019-05-15 07:13:22
7 2019-05-15 07:13:23
8 2019-05-15 07:13:24
9 2019-05-15 07:13:25
Run Code Online (Sandbox Code Playgroud)

查看DataFrame.query 的 Pandas文档,特别是关于本地变量引用的 udsing@前缀的提及。在这种情况下,我们pd.Timestamp使用本地别名ts来引用能够提供时间戳字符串


fan*_*ous 11

如果日期在索引中,则只需:

df['20160101':'20160301']
Run Code Online (Sandbox Code Playgroud)


Ekr*_*dal 11

按日期过滤数据框的最短方法:假设您的日期列是 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']
Run Code Online (Sandbox Code Playgroud)


Har*_*rry 9

因此,在加载 csv 数据文件时,我们需要将日期列设置为索引,如下所示,以便根据日期范围过滤数据。现在已弃用的方法不需要此方法:pd.DataFrame.from_csv()。

如果只想显示一月到二月这两个月的数据,比如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'] 
Run Code Online (Sandbox Code Playgroud)

这已经过测试适用于 Python 3.7。希望你会发现这很有用。


uhe*_*etz 7

我还不允许写任何评论,所以我会写一个答案,如果有人会阅读所有评论并找到这个答案。

如果数据集的索引是日期时间并且您只想按(例如)月份过滤它,您可以执行以下操作:

df.loc[df.index.month == 3]
Run Code Online (Sandbox Code Playgroud)

这将在 3 月之前为您过滤数据集。

  • 我认为有一个小错字,应该是`df.loc[df.index.month == 3]` (2认同)

pak*_*a79 5

怎么用 pyjanitor

它有很酷的功能。

pip install pyjanitor

import janitor

df_filtered = df.filter_date(your_date_column_name, start_date, end_date)
Run Code Online (Sandbox Code Playgroud)


Ern*_*une 5

您可以通过执行以下操作来选择时间范围:df.loc['start_date':'end_date']


小智 5

import pandas as pd
Run Code Online (Sandbox Code Playgroud)

第 1 步:使用pd.to_datetime()将日期列转换为 pandas 日期时间

df['date']=pd.to_datetime(df["date"],unit='s')
Run Code Online (Sandbox Code Playgroud)

步骤2:以任何预定方式执行过滤(即2个月)

df = df[(df["date"] >"2022-03-01" & df["date"] < "2022-05-03")]
Run Code Online (Sandbox Code Playgroud)