按日期过滤 Pandas DataFrames [英] Filtering Pandas DataFrames on dates

查看:53
本文介绍了按日期过滤 Pandas DataFrames的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

解决方案

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

例如:

df.loc['2014-01-01':'2014-02-01']

在此处查看详细信息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 已弃用.

I have a Pandas DataFrame with a 'date' column. Now I need to filter out all rows in the DataFrame that have dates outside of the next two months. Essentially, I only need to retain the rows that are within the next two months.

What is the best way to achieve this?

解决方案

If date column is the index, then use .loc for label based indexing or .iloc for positional indexing.

For example:

df.loc['2014-01-01':'2014-02-01']

See details here http://pandas.pydata.org/pandas-docs/stable/dsintro.html#indexing-selection

If the column is not the index you have two choices:

  1. Make it the index (either temporarily or permanently if it's time-series data)
  2. df[(df['date'] > '2013-01-01') & (df['date'] < '2013-02-01')]

See here for the general explanation

Note: .ix is deprecated.

这篇关于按日期过滤 Pandas DataFrames的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆