【问题标题】:Column contains column列包含列
【发布时间】:2019-07-01 15:17:21
【问题描述】:

我想看看我的数据框列 A 的每一行中是否包含列 B 中的值。

df = pd.DataFrame({'A': ["Is it 54321?", "Is it 4321?", "Is it 321?"],
                   'B': [54321, 54321, 54321]})

我试过了:

df["C"] = df["A"] .str .contains(df["B"])

我想要:

'C': [1,0,0]

但我得到了:

TypeError: 'Series' objects are mutable, thus they cannot be hashed

【问题讨论】:

    标签: python pandas contains


    【解决方案1】:

    或者:

    df['C']=df.A.str.contains(r'\b(?:{})\b'.format('|'.join(df.B.astype(str)))).astype(int)
    print(df)
    
                  A      B  C
    0  Is it 54321?  54321  1
    1   Is it 4321?  54321  0
    2    Is it 321?  54321  0
    

    【讨论】:

    【解决方案2】:

    这是另一种方法:

    df['C'] = (df['B'] == df['A'].str.rstrip('?').str.split(' ').str[-1].astype(int)) * 1
    

    【讨论】:

    • 虽然这个答案有效,但它太具体了。也就是说,它只适用于预期数字是列中最后一个单词的字符串,而不适用于例如“54321 is my number”的字符串。
    • 是的,给定的例子在这个意义上是误导性的。
    【解决方案3】:

    我发现它可以作为一个函数工作:

    def fun (A,B):
        if str(B) in A:
            return 1
        else:
            return 0
    f = np.vectorize(fun, otypes=[float])
    df["C"] = f(df['A'],df['B'])
    

    【讨论】:

    • 不鼓励在 StackOverflow 上仅使用代码的答案,也许您可​​以包括为什么 OP 犯了错误以及如何解决它。谢谢!
    【解决方案4】:

    您可以简化代码:

    def fun (A,B):
        return str(B) in str(A) # Edit: A to str(A)
    
    f = np.vectorize(fun, otypes=[int])
    df["C"] = f(df['A'],df['B'])
    

    或者使用列表推导:

    df["C"] = [int(str(B) in A) for A, B in zip(df['A'],df['B'])]
    

    【讨论】:

    • 警告:当 'A' 是“是 22 吗?”时,此方法将返回 'True'而“B”是“2”。
    • @kevins_1 - 是的,它测试数字。
    • 我喜欢我尝试的简化版本。这是测试数字的列表理解。
    【解决方案5】:

    我已经接受了这个线程上的各种答案,但我遇到了问题,如下所述: Column contains column 1

    感谢文本的回答:

    如果您确实希望 12 在 123 中:

    df = df.dropna()
    df['C'] = [str(y) in x for x , y in zip(df.A,df.B)]
    print(df)
    

    或者如果你不希望 12 出现在 123 中:

    df = df.dropna()
    df['C'] = [str(y) in x for x , y in zip(df.A.str.split(' '),df.B)]
    print(df)
    
    猜你喜欢
    • 2019-09-22
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 2018-07-19
    • 1970-01-01
    相关资源
    最近更新 更多