python - 选择 Pandas 中的行,其中一列中的值是另一列中值的子字符串

标签 python pandas dataframe

下面有一个数据框

>df = pd.DataFrame({'A':['apple','orange','grape','pear','banana'], \
                    'B':['She likes apples', 'I hate oranges', 'This is a random sentence',\
                         'This one too', 'Bananas are yellow']})

>print(df)

    A       B
0   apple   She likes apples
1   orange  I hate oranges
2   grape   This is a random sentence
3   pear    This one too
4   banana  Bananas are yellow

我正在尝试获取 B 列包含 A 列中的值的所有行。

预期结果:

    A       B
0   apple   She likes apples
1   orange  I hate oranges
4   banana  Bananas are yellow

我只能使用

获取一行
>df[df['B'].str.contains(df.iloc[0,0])]

    A       B
0   apple   She likes apples

我怎样才能获取所有这些行?

最佳答案

使用DataFrame.apply将两个值都转换为较低值并测试包含 in 并按 boolean indexing 过滤:

df = df[df.apply(lambda x: x.A in x.B.lower(), axis=1)]

或者列表理解解决方案:

df = df[[a in b.lower() for a, b in zip(df.A, df.B)]]

print (df)
        A                   B
0   apple    She likes apples
1  orange      I hate oranges
4  banana  Bananas are yellow

关于python - 选择 Pandas 中的行,其中一列中的值是另一列中值的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59208708/

相关文章:

python - Geopandas 没有属性 hvplot

python - 如何在 Pandas DataFrame where 子句中使用特定列的值?

python - 使用 PdfMiner 和 PyPDF2 合并列提取文本

python-3.x - 使用 seaborn 绘制多个直方图

python - 列表中对的乘积之和

python - 如何更新 python pandas 中的交叉表值

python - 从导入的模块编辑类

python - 当一列与其他列分开时如何选择 DataFrame 列?

python-3.x - 在 For 循环中,使用 bs4,该函数如何返回 df (作为列)并将其插入到最终的巨型 df 中?

python - 理解级别 =0 和 group_keys