【问题标题】:Pandas: select dataframe rows only if the values in a specific column start withPandas:仅当特定列中的值以开头时才选择数据框行
【发布时间】:2017-07-03 04:27:13
【问题描述】:

我有以下数据框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

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

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

但是如何选择所有不以336开头的行?

PS:就我而言,33603365 是字符串。

【问题讨论】:

    标签: python pandas dataframe slice


    【解决方案1】:

    我会使用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
    

    【讨论】:

    • 忘了说。您将如何组合两个或多个条件,例如336545?你可以在访问器中使用or 吗?
    • @CF84 你可以提供一个元组给startswith。例如,df[~df.B.str.startswith(('112', '336', '556'))].
    猜你喜欢
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    相关资源
    最近更新 更多