【问题标题】:How can I filter a dataframe of dates with other date in Python?如何在 Python 中过滤具有其他日期的日期数据框?
【发布时间】:2019-04-04 12:59:57
【问题描述】:

我在 python 中使用 pandas 完成了这个数据框:

        0
0   2018-06-29
1   2018-10-29
2   2019-02-28
3   2019-06-29
4   2019-10-29
5   2020-02-29
6   2020-06-29
7   2020-10-29
8   2021-02-28

然后我有一个日期是下一个:

[datetime.date(2020, 2, 29)]

我想过滤数据框以仅获取

Seleccion = df.loc[df[0] < date]
Arrays were different lengths: 9 vs 1

我不知道是否有办法做到这一点,但如果有,任何帮助都是完美的。 感谢您抽出宝贵时间。

【问题讨论】:

  • 你不需要.iloc 只需selection = df[df['0'] &lt; date]
  • 输出是一样的@TBurgis
  • 请看下面的答案。我的评论是正确的。

标签: python pandas date dataframe filtering


【解决方案1】:

您的示例中“日期”的值是什么? 如果是

date = [datetime.date(2020, 2, 29)]

那么发生错误是正常的,因为您正在将系列与数组进行比较。

你想做的是

date = datetime.date(2020, 2, 29)
df[df[0] < date]

因为现在您正在将 Series 与常量进行比较,而 pandas 能够将其转换为 Series 上的逐行比较。

在您将 Series 与数组进行比较之前(即使它只有一个元素),并且要使其正常工作,数组必须具有与 Series 相同的长度。

【讨论】:

  • 你在df.[df[0] &lt; date]有错字,去掉.
  • 这行得通,但如果有办法将数组转换为 datetime.date 对象? @TBurgis
  • 您将哪个变量称为“数组”?我假设 df[0] 的数据类型是 datetime.date 对象。如果您需要转换它,请使用 pd.to_datetime 然后查看link
猜你喜欢
  • 2019-01-15
  • 1970-01-01
  • 2022-11-23
  • 2020-10-04
  • 1970-01-01
  • 2018-09-29
  • 1970-01-01
  • 2016-08-11
  • 1970-01-01
相关资源
最近更新 更多