简体   繁体   English

如何在Python中过滤带有其他日期的日期数据框?

[英]How can I filter a dataframe of dates with other date in Python?

I have this dataframe in python done in pandas: 我在熊猫中用python完成了这个数据框:

        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

Then I have a date that is the next one: 然后我有一个约会,下一个约会:

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

I want to filter the data frame to get just the dates that are <= that the date I have. 我想过滤数据框以仅获取小于等于我拥有的日期的日期。 I tried this with loc[] but I get the next output: 我用loc []尝试了一下,但是得到了下一个输出:

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

I don't know if there is a way to do that, but if it is, any help would be perfect. 我不知道是否有办法做到这一点,但是如果有的话,任何帮助都是完美的。 Thank you for taking your time. 感谢您抽出宝贵的时间。

What is the value of "date" on your example? 您的示例中“日期”的值是什么? If it is 如果是

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

then it is normal the error is happening because you are comparing a series to an array. 则错误是正常的,因为您正在将序列与数组进行比较。

What you want to do is 你想做的是

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

because now you are comparing a Series with a constant, and pandas is able to transform it into a comparison row-wise over the Series. 因为现在您正在将一个系列与一个常数进行比较,而pandas可以将其转换为该系列的逐行比较。

Before you were comparing a Series with an array (even if it has a single element), and for that to work, the array had to have the same length as the Series. 在将Series与数组进行比较(即使它只有一个元素)之前,为了使数组起作用,数组必须具有与Series相同的长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM