![](/img/trans.png)
[英]If partial string in the same pandas column match then update the value in another column
[英]pandas - If partial string match exists, put value in new column
我在 pandas 中有一个棘手的问题要解决。 我之前曾将此线程称为解决方案,但它不是我想要的。
以具有两列的 dataframe 为例:
df = pd.DataFrame([['Mexico', 'Chile'], ['Nicaragua', 'Nica'], ['Colombia', 'Mex']], columns = ["col1", "col2"])
我首先要检查第 2 列中的每一行以查看该值是否存在于第 1 列中。这是检查完整和部分字符串。
df['compare'] = df['col2'].apply(lambda x: 'Yes' if df['col1'].str.contains(x).any() else 'No')
我可以检查我是否有部分或完整字符串的匹配项,这很好,但不是我需要的。 这是 dataframe 现在的样子:
我真正想要的是第 1 列中的值与第 2 列中的值匹配。 我一直无法弄清楚如何将它们关联起来
我想要的结果如下所示:
这是一种“无熊猫”的方法。 可能效率不高,但它完成了工作:
def compare_cols(match_col, partial_col):
series = []
for partial_str in partial_col:
for match_str in match_col:
if partial_str in match_str:
series.append(match_str)
break # matches to the first value found in match_col
else: # for loop did not break = no match found
series.append(None)
return series
df = pd.DataFrame([['Mexico', 'Chile'], ['Nicaragua', 'Nica'], ['Colombia', 'Mex']], columns = ["col1", "col2"])
df['compare'] = compare_cols(match_col=df.col1, partial_col=df.col2)
请注意,如果col2
中的字符串与col1
中的多个字符串匹配,则使用第一个匹配项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.