![](/img/trans.png)
[英]Python DataFrame: One-Hot Encode Rows Containing a Specific Substring
[英]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.