繁体   English   中英

如果ID存在于其他数据帧中,则Python Pandas数据帧会在新列中添加“1”

[英]Python Pandas dataframe add “1” in new column if ID exists in other dataframe

我有两个带有客户ID的数据框(标记为“C_ID”)以及一年的访问次数。

如果客户也在2009年购物,我想在我的2010数据框中添加一列。所以我需要创建一个循环来检查2010年的C_ID是否存在于2009年,添加1,否则为0。

我使用此代码并没有工作:(没有错误消息,没有任何反应)

for row in df_2010.iterrows():
    #check if C_ID exists in the other dataframe
    check = df_2009[(df_2009['C_ID'] == row['C_ID'])]

    if check.empty:
        #ID not exist in 2009 file, add 0 in new column
        row['shopped2009'] = 0

    else:
        #ID exists in 2009 file, add 1 into same column
        row['shopped2009'] = 1

你可以使用dataframe.isin()

% timeit df_2010['new'] = np.where(df_2010['C_ID'].isin(df_2009['C_ID']), 1, 0)

最佳3:每循环384μs

正如@Kris建议的那样

%timeit df_2010['new'] = (df_2010['C_ID'].isin(df_2009['C_ID'])).astype(int)

最佳3:每循环584μs

要么

df_2010['new'] = df_2010['C_ID'].isin(df_2009['C_ID'])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM