【问题标题】:How to select rows containing a specific substring within a given position - python如何在给定位置选择包含特定子字符串的行 - python
【发布时间】:2021-01-29 19:01:45
【问题描述】:

我正在使用如下所示的大数据框:

     id      time1      time2   data    
0   id1   06:24:00   06:24:00      A
1   id2   07:24:00   07:24:00      A
2   id3   08:24:00   08:24:00      B

我想以23:xx:yy 格式选择所有具有time1 和/或time2 的行。

我尝试使用以下代码,但速度极慢,因此我正在寻找更高效的方法:

list_ = list()

for idx in df.index:
    if ('23' in df.time1[:2]) | ('23' in df.time2[:2]):
        list_.append(df.loc[df.index == idx])  ###--- Here I wanted to get a list of indexes so I could do a simple df.loc[] afterward

我也尝试了以下代码,但都引发了错误:

df.loc[df.time1[:2] == '23']
df.loc['23' in df.time1[:2]]
df[df.time1[:2].str.contains('23')]

> IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match

有没有办法做到这一点?任何帮助将不胜感激。

【问题讨论】:

    标签: python python-3.x pandas substring


    【解决方案1】:

    Series.str.startswith| 一起用于按位OR& 用于按位AND

    df[df.time1.str.startswith('23') | df.time2.str.startswith('23')]
    

    如果要比较字符串的前 2 个值,请添加 str[:2] 进行索引:

    df[df.time1.str[:2].eq('23') | df.time2.str[:2].eq('23')]
    

    【讨论】:

    • 非常感谢,确实很有效率!
    • 还要解释一下为什么OP目前的做法很慢?
    • @AbhinavMathur - 因为有行选择df.loc[df.index == idx]
    【解决方案2】:

    要添加到 jezrael 答案,如果列数据是日期时间,您可以这样做

    df[(df.time1.dt.hour == 23)|(df.time2.dt.hour == 23)]
    

    【讨论】:

    • 是的,它实际上是日期时间,谢谢,下次我会记住这个提示!
    • 我也是这么想的;但在我的情况下是df.time1.dt.hour == 23,否则熊猫会抱怨Series没有hour
    猜你喜欢
    • 2015-10-17
    • 2014-01-29
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 2021-12-13
    • 2021-01-30
    • 2018-12-13
    相关资源
    最近更新 更多