0

I have this dataframe in python done in 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

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:

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.

3
  • You don't need the .iloc just do selection = df[df['0'] < date] Commented Oct 31, 2018 at 11:16
  • The output is the same @TBurgis Commented Oct 31, 2018 at 11:20
  • See the answer below. My comment is correct. Commented Oct 31, 2018 at 11:41

1 Answer 1

1

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.

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You have a typo in df.[df[0] < date], get rid of the .
That works but if there a way to convert the array in a datetime.date object? @TBurgis
Which variable are you calling "the array"? I assumed the datatype of df[0] was a datetime.date object. If you need to convert it use the pd.to_datetime and then look into link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.