You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R中grepl结合dplyr filter的Python等价实现技术问询

Replicating R's dplyr Filter Logic in Pandas

Got it, let's sort this out! The problem with using isin() here is that it only returns rows where the entire Countries string exactly matches one of your target values. But we need to catch rows where either Brazil or Argentina appears anywhere in the comma-separated list—just like your R code does with grepl or the strsplit/lapply approach.

Here are two pandas solutions that mirror your R implementations:

Solution 1: Using str.contains() (Equivalent to dplyr + grepl)

This uses regex to search for either "Brazil" or "Argentina" as a substring in the Countries column, just like grepl('(Brazil|Argentina)', Countries) in R:

import pandas as pd

df = pd.DataFrame(dict(
    Countries=['Brazil','Venezuela','Brazil, Colombia, Paraguay','Argentina','Peru','Andorra,Argentina,Chile,Uruguay'],
    Code=[1,2,3,4,5,6]
))

# Filter rows where Countries contains Brazil or Argentina
filtered_df = df[df['Countries'].str.contains('Brazil|Argentina', regex=True)]
print(filtered_df)

Solution 2: Split, Clean, and Check Membership (Mirroring strsplit/lapply)

This replicates your second R approach: splitting the string, cleaning whitespace, then checking if any element matches your target countries:

import pandas as pd

df = pd.DataFrame(dict(
    Countries=['Brazil','Venezuela','Brazil, Colombia, Paraguay','Argentina','Peru','Andorra,Argentina,Chile,Uruguay'],
    Code=[1,2,3,4,5,6]
))

targets = {'Brazil', 'Argentina'}  # Using a set for faster membership checks

# For each row: split by commas, strip spaces, check if any match targets
has_target = df['Countries'].apply(
    lambda row: any(country.strip() in targets for country in row.split(','))
)

filtered_df = df[has_target]
print(filtered_df)

Expected Output for Both Solutions

Countries  Code
0                            Brazil     1
2       Brazil, Colombia, Paraguay     3
3                         Argentina     4
5  Andorra,Argentina,Chile,Uruguay     6

Both methods will give you the exact result you're looking for, matching the output from your R code.

内容的提问来源于stack exchange,提问作者bzimons

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 19:48:16