繁体   English   中英

python pandas - 检查列中的部分字符串是否存在于其他列中

[英]python pandas - Check if partial string in column exists in other column

取一个样本数据集:

df = pd.DataFrame([['Mexico', 'Chile'], ['Nicaragua', 'Nica'], ['Colombia', 'Mex']], columns = ["col1", "col2"])

dataframe 看起来像这样:

我有两列。 我想检查第二列中的值是否存在于第一列中。 这包括检查部分字符串。

所需的 output 是:

在此处输入图像描述

我能够比较第二列中每一行的整个值,但这不考虑部分字符串:

df['compare'] = np.where(df['col2'].isin(df['col1']), 'yes', 'no')

我还能够检查列中是否存在单个值,该值检查部分字符串但不包括“col2”列中的每一行。

df['compare'] = df['col1'].str.contains('Mex')

我怎样才能同时做这两个?

这看起来像一个昂贵的操作。 你可以试试:

df['col2'].apply(lambda x: 'Yes' if df['col1'].str.contains(x).any() else 'No')

Output:

0     No
1    Yes
2    Yes
Name: col2, dtype: object

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM