【问题标题】:Create new column conditionally from other df columns从其他 df 列有条件地创建新列
【发布时间】:2021-01-04 17:44:21
【问题描述】:

如果满足 df2 的两列中的两个条件,我想在 df1 中创建一个新的布尔列。例如:

df1:
   ID         Date
01234    8-23-2020
01234    8-26-2020
01235    8-24-2020
01235     9-3-2020
01236     9-1-2020

df2:
   id       visit
01234    8-23-2020
01235     9-3-2020

我想在 df1 中仅对 df2 中的访问设置为“真”,结果如下:

df1:
   ID         Date    In_store
01234    8-23-2020        1
01234    8-26-2020        0
01235    8-24-2020        0
01235     9-3-2020        1
01236     9-1-2020        0

我试过了:

pos_id = df2['id'].tolist()
pos_date = df2['visit'].tolist()

for row in df:
    if df1['ID'].isin(pos_id) and df1['Date'].isin(pos_visit):
        df1['In_store'] = 1
    else: 
        df1['In_store'] = 0

但我得到: "ValueError: Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。"

我已经试过了:

for row in df:
    if df1['ID'] == df2['ID'] and df1['Date'] == df2['Date']:
        df1['In_store'] = 1
    else: 
        df1['In_store'] = 0

但我得到: “ValueError: Can only compare the same-labeled Series objects”即使在将列重命名为相同之后也是如此。

我错过了什么? 谢谢

【问题讨论】:

    标签: python pandas dataframe if-statement


    【解决方案1】:

    这本质上是合并:

    merged = df1.merge(df2, left_on=['ID','Date'], right_on=['id','visit'], how='left')
    
    df1['In_store'] = merged['visit'].notna().astype(int)
    

    输出:

         ID       Date  In_store
    0  1234  8-23-2020         1
    1  1234  8-26-2020         0
    2  1235  8-24-2020         0
    3  1235   9-3-2020         1
    4  1236   9-1-2020         0
    

    【讨论】:

    • 谢谢,这有效。不幸的是,我最后的新列中的一些 id 与 df2 中的 id 不匹配。我将进一步挖掘我可能错过的内容
    猜你喜欢
    • 2023-01-23
    • 2014-11-25
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多