Pandas:select 数据框行仅当特定列中的值以

Pandas: select dataframe rows only if the values in a specific column start with

我有以下数据框df1

    X           Y           A       B
0   484         408         10      3360
1   478         415         24      3365
2   504         452         31      yes
3   613         551         33      maybe
4   663         665         39      no

我知道如何 select 列 Byes 或任何其他特定值的行:

df1.loc[df1['B'] == 'yes']

但是我如何 select 所有 不以 336 开头的行

PS:在我的例子中,33603365 是字符串。

我会使用 df[~df.B.str.startswith('336')] 之类的东西,使用 str 访问器。例如,

>>> df = pd.DataFrame({'B': ['3360', '3365', 'yes', 'maybe', 'no']})
>>> df[~df.B.str.startswith('336')]
       B
2    yes
3  maybe
4     no

如果您要检查多个字符串,startswith 接受一个前缀元组。

>>> df[~df.B.str.startswith(('112', '336', 'n'))]
       B
2    yes
3  maybe