【问题标题】:Python Pandas dataframe add "1" in new column if ID exists in other dataframe如果 ID 存在于其他数据框中,则 Python Pandas 数据框在新列中添加“1”
【发布时间】:2017-06-23 22:16:35
【问题描述】:

我有两个数据框,其中包含客户 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

【问题讨论】:

    标签: python loops pandas dataframe


    【解决方案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'])
    

    【讨论】:

    • 这太完美了——你真是个天才!谢谢你
    • 很好的答案@VaishaliGarg。一个小建议可能是使用.astype(int) 而不是np.where(..)
    • 谢谢@Kris,有什么好处?
    • 优势很小,真的.. 主要是符号。也许也有一些表现,但我对此表示怀疑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 2021-10-08
    • 1970-01-01
    • 2019-08-20
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    相关资源
    最近更新 更多