Pandas,搜索dataframe1的哪些列的值在dataframe2的列中,以及哪一行

问题描述 投票:0回答:1

df1中有一个日期数据框。

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

df2中,我有一个连续的时间序列(每天)。

        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

由于df2长于df1,因此它们是独立的数据帧。

我想在df2中生成一列,如果1中存在日期,则包含df1,如果0中不存在Date,则包含df1。没有编写循环就可以吗?

我知道np.where()和其他熊猫函数会有所帮助,如果2个数据帧的长度相同。这可能吗?

想要的结果:

        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
python pandas dataframe
1个回答
1
投票

使用isin方法检查列表中是否存在值

df2['Date'].isin(df1['Date']).astype(int)
© www.soinside.com 2019 - 2024. All rights reserved.