如何 select 包含给定位置内特定子字符串的行 - 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
我想 select 所有具有 time1
and/or time2
的行 23:xx:yy
格式。
我尝试使用以下代码,但它非常慢,所以我正在寻找更高效的代码:
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 答案,如果列数据是 Datetime,你可以这样做
df[(df.time1.dt.hour == 23)|(df.time2.dt.hour == 23)]
我正在使用如下所示的大型数据框:
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
我想 select 所有具有 time1
and/or time2
的行 23:xx:yy
格式。
我尝试使用以下代码,但它非常慢,所以我正在寻找更高效的代码:
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 答案,如果列数据是 Datetime,你可以这样做
df[(df.time1.dt.hour == 23)|(df.time2.dt.hour == 23)]