【问题标题】:Lookup a value and if it is present in another df, return text in two new columns查找一个值,如果它存在于另一个 df 中,则在两个新列中返回文本
【发布时间】:2022-01-17 20:28:00
【问题描述】:

我已经使用以下脚本达到了一定程度,即使使用“is.in”这样的函数,我也无法完全理解它,可能是因为在此之前我从未使用过它。

输入df1:

    ID  Alternative ID
0   152503  009372
1   249774  249774
2   062005  196582
3   185704  185704
4   081231  081231
5   081231  062085
6   912568  222416
7   196782  195122

输入 df2:

    New_ID
0   498109
1   081231
2   231051
3   062005
4   152503
5   967272
6   875612

我的想法是我想检查“ID”的值是否与 df1 中的“Alternative ID”上的值匹配。如果他们这样做,它应该分别在名为“Result_1”和“Result_2”的两个新列上返回“Match”和“Correct”。对于那些不匹配的,查找它们是否全部出现在 df2 的“New_ID”列中。如果它们在上面提到的那两列上分别返回“新匹配”和“好”的值。如果它们不存在,则返回“不匹配”和“错误”。

对于这个任务的第一部分,这是我使用的代码:

def compl(df1):

    if (df1['ID'] == df1['Alternative ID']):
        return 'Match', 'Correct'
    elif (df1['ID'] != df1['ID']):

这里找不到下一步基本上检查不匹配的值是否在df2等中。

df1[['Result_1', 'Result_2']] = df1.apply(compl, axis = 1, result_type = 'expand')

理想的输出 ->

ID  Alternative ID  Result_1    Result_2
0   152503  009372  NEW Match   Good
1   249774  249774  Match       Correct
2   062005  196582  NEW Match   Good
3   185704  185704  Match       Correct
4   081231  062085  Match       Correct
5   912568  222416  Not Match   Error
6   196782  195122  Not Match   Error

任何建议/方法将不胜感激

【问题讨论】:

    标签: python pandas dataframe numpy


    【解决方案1】:

    np.select 与您的条件和所需值一起使用。对于每个条件的真实性,函数select 将映射给定的值。

    import numpy as np
    
    conditions = [
        df1['ID'] == df1['Alternative ID'],
        df1['ID'].isin(df2['New_ID'])
    ]
    values_result1 = ['Match', 'New match']
    values_result2 = ['Correct', 'Good']
    
    df1['Result_1'] = np.select(conditions, values_result1, 'No match')
    df1['Result_2'] = np.select(conditions, values_result2, 'Error')
    

    输出

           ID  Alternative ID   Result_1 Result_2
    0  152503            9372  New match     Good
    1  249774          249774      Match  Correct
    2   62005          196582  New match     Good
    3  185704          185704      Match  Correct
    4   81231           81231      Match  Correct
    5   81231           62085  New match     Good
    6  912568          222416   No match    Error
    7  196782          195122   No match    Error
    

    注意:您的答案经过更多调整后将起作用。但它会比上面的向量化方法慢很多。尽量不要使用apply,直到别无他法。

    【讨论】:

    • 好的,知道了!最初,我认为使用 apply 是处理庞大数据框的最佳方式。再次感谢。
    • apply 将为您的案例中的每一行迭代并运行该函数。上述矢量化方法将在O(n) 时间内完成,无需直接迭代。因此,减少时间。 @Alexchristof20
    猜你喜欢
    • 2018-04-10
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 2022-12-03
    相关资源
    最近更新 更多