1

I am trying to compare two Pandas DatetineIndexs with different lengths. I want to simply add a new column to my larger Dataframe (df) and place 1 where it matches the smaller DatetineIndex (events).

I tried

df['filter'] = np.where(df.index == tEvents, 1, np.nan)

but I get "ValueError: Lengths must match to compare"

I've been stuck here longer than I like to admit

Comparing different python datetime index with different lengths

BillyRay
  • 413
  • 2
  • 10
  • 24
  • 1
    `tEvents` and `df.index` are different lengths. I believe you want `df.index in tEvents` not `df.index == tEvents` – W Stokvis Jul 20 '18 at 17:34
  • 1
    @W Stokvis, thanks I believe this is what I am looking for. Can you post it as an answer so I can mark it as solved! – BillyRay Jul 20 '18 at 17:40

1 Answers1

3

tEvents and df.index are different lengths. df.index == tEvents looks to compare the two lists.

You want to check if an element in df.index is in tEvents. Thus replace df.index == tEvents with df.index.isin(tEvents)

To see add a True or false value if date matches, use DataFrame.isin()

W Stokvis
  • 1,409
  • 8
  • 15
  • 3
    `df.index in tEvents` won't work, because indexes aren't hashable. That's trying to check if the `df.index` object itself, not its constituent elements, is in tEvents. You probably want `df.index.isin(tEvents)`. – DSM Jul 20 '18 at 17:58
  • @DSM adjusted the answer. Thanks for the feedback. – W Stokvis Jul 20 '18 at 17:59