python - Pandas : select row where column A does not begin with column B

标签 python pandas dataframe

我想选择数据框中 A 列(字符串)不以 B 列(字符串)开头的所有行。我使用了

df[not df['A'].str.startswith(df['B']) ] 

但它显示的不是 bool 值。

例如:

      A       B


 1. abcdef  abc
 2. ab      cd
 3. ef      g

那么需要的输出是:

例如:

     A       B

 1. ab       cd
 2. ef       g

请帮忙。

最佳答案

你可以这样做:

In [250]: data={'A': ['abcdef', 'ab', 'ed'], 
     ...:         'B': ['abc', 'cd','g']} 
     ...: df = pd.DataFrame(data)

In [251]: df                                                                                                                                                                                                
Out[251]: 
        A    B
0  abcdef  abc
1      ab   cd
2      ed    g

In [248]: df[~df.A.str.contains('|'.join(df.B))]                                                                                                                                                            
Out[248]: 
    A   B
1  ab  cd
2  ed   g

关于python - Pandas : select row where column A does not begin with column B,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61718616/

相关文章:

python - 按两列分组, Pandas python 中第三列的最大值

python - Pandas DataFrame : Unusual Behaviour with json. 转储(额外的双引号)

python - 为什么optimal_count没有给出正确的结果?

python - pandas 在 to_csv 中转义回车

python - 融化 pandas DataFrame 并使用值作为列?

python - 我应该使用哪个语句来替换创建虚拟变量的自定义函数以提高 python 中的速度?

Pandas:如何获取每组中的前 2、中 2 和底 2 行

python - 使用 pandas 数据框列中的正则表达式删除 URL 字符串的一部分

python - 子字符串 SQL 查询变量

python - 对齐 pandas 中的两列字符串(递归合并字符串直到匹配)