Saturnix
Saturnix

Reputation: 10554

Pandas, search which values of column of dataframe1 are in column of dataframe2, and in which row

I have, in df1, a dataframe of dates.

0   03/01/2007
1   16/02/2007
2   16/03/2007
3   20/04/2007
4   18/05/2007

In df2 I have a continuos time serie (daily).

        Date  DailyEquity
1 2007-01-04          0.0
2 2007-01-05         -5.0
3 2007-01-06          0.0
4 2007-01-07          0.0
5 2007-01-08          5.0

These are separate dataframes since df2 is longer than df1.

I'd like to generate a column in df2 such that it contains 1 if Date is present in df1, and 0 if Date is not present in df1. Is this possible without writing loops?

I know of np.where() and other pandas functions that would help in this, if the 2 dataframes were of the same length. Is this possible?

Wanted result:

        Date  DailyEquity  Column
1 2007-01-04          0.0  0    # <-- "2007-01-04" is not in df1
2 2007-01-05         -5.0  0    # <-- "2007-01-05" is not in df1
3 2007-01-06          0.0  0    # <-- ecc...
4 2007-01-07          0.0  0    # <-- "1" if date is in df1
5 2007-01-08          5.0  0

Upvotes: 0

Views: 42

Answers (1)

splash58
splash58

Reputation: 26153

Use isin method to check that a value present in a list

df2['Date'].isin(df1['Date']).astype(int)

Upvotes: 1

Related Questions