簡體   English   中英

如何在給定位置選擇包含特定子字符串的行 - python

[英]How to select rows containing a specific substring within a given position - python

我正在使用一個看起來像這樣的大數據框:

     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

有沒有辦法做到這一點? 任何幫助將不勝感激。

使用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')]

要添加到 jezrael 答案,如果列數據是日期時間,您可以這樣做

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM