ValueError: Series lengths must match to compare when matching dates in Pandas

前端 未结 2 1015
借酒劲吻你
借酒劲吻你 2020-12-17 16:13

I apologize in advance for asking such a basic question but I am stumped.

This is a very simple, dummy example. I\'m having some issue matching dates in Pandas and I

2条回答
  •  时光说笑
    2020-12-17 16:57

    You say:

    some_date = df.iloc[1:2]['Date']  # gives 2016-01-01
    

    but that's not what it gives. It gives a Series with one element, not simply a value -- when you use [1:2] as your slice, you don't get a single element, but a container with one element:

    >>> some_date
    1   2016-01-01
    Name: Date, dtype: datetime64[ns]
    

    Instead, do

    >>> some_date = df.iloc[1]['Date']
    >>> some_date
    Timestamp('2016-01-01 00:00:00')
    

    after which

    >>> df[(df['ID']==some_id) & (df['Date'] == some_date)] 
       ID       Date
    0   1 2016-01-01
    

    (Note that there are more efficient patterns if you have a lot of some_id and some_date values to look up, but that's a separate issue.)

提交回复
热议问题