【问题标题】:Pandas Row Select Where String Starts With Any Item In List熊猫行选择字符串以列表中任何项目开头的位置
【发布时间】:2018-04-28 05:43:10
【问题描述】:

我想根据特定的字符串列选择 pandas 数据框中的行子集,其中值以列表中任意数量的值开头。

这个的一个小版本:

df = pd.DataFrame({'a': ['aa10', 'aa11', 'bb13', 'cc14']})
valids = ['aa', 'bb']

所以在这种情况下,我只想要aaabb 开头的那些行。

【问题讨论】:

    标签: pandas


    【解决方案1】:

    你需要startswith

    df.a.str.startswith(tuple(valids))
    Out[191]: 
    0     True
    1     True
    2     True
    3    False
    Name: a, dtype: bool
    

    使用原始df过滤后

    df[df.a.str.startswith(tuple(valids))]
    Out[192]: 
          a
    0  aa10
    1  aa11
    2  bb13
    

    【讨论】:

    • 效果很好。非常感谢您的出色帮助。
    猜你喜欢
    • 2018-08-15
    • 2020-05-12
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 2013-02-03
    相关资源
    最近更新 更多