查找 Pandas 系列包含包含字符的元素的索引
Find indices of where Pandas Series contains element containing character
示例:
import pandas as pd
arr = pd.Series(['a',['a','b'],'c'])
我想获取系列包含包含 'a'
的元素所在位置的索引。所以我想取回索引 0
和 1
。
我试过写
arr.str.contains('a')
但是这个returns
0 True
1 NaN
2 False
dtype: object
虽然我想要 return
0 True
1 True
2 False
dtype: object
使用 Series.str.join() 将单元格中的 lists/arrays 连接成一个字符串,然后使用 .str.contains('a')
:
In [78]: arr.str.join(sep='~').str.contains('a')
Out[78]:
0 True
1 True
2 False
dtype: bool
使用 Series.apply
和 Python 的 in
关键字,它适用于列表和字符串
arr.apply(lambda x: 'a' in x)
如果您的 Series
中没有任何 NaN 值,这将正常工作,但如果有,您可以使用:
arr.apply(lambda x: 'a' in x if x is not np.nan else x)
这比使用 Series.str
快得多。
基准:
%%timeit
arr.str.join(sep='~').str.contains('a')
参加:249 µs ± 4.83 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%%timeit
arr.apply(lambda x: 'a' in x)
需要:70.1 µs ± 1.68 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%%timeit
arr.apply(lambda x: 'a' in x if x is not np.nan else x)
需要:69 µs ± 1.6 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
示例:
import pandas as pd
arr = pd.Series(['a',['a','b'],'c'])
我想获取系列包含包含 'a'
的元素所在位置的索引。所以我想取回索引 0
和 1
。
我试过写
arr.str.contains('a')
但是这个returns
0 True
1 NaN
2 False
dtype: object
虽然我想要 return
0 True
1 True
2 False
dtype: object
使用 Series.str.join() 将单元格中的 lists/arrays 连接成一个字符串,然后使用 .str.contains('a')
:
In [78]: arr.str.join(sep='~').str.contains('a')
Out[78]:
0 True
1 True
2 False
dtype: bool
使用 Series.apply
和 Python 的 in
关键字,它适用于列表和字符串
arr.apply(lambda x: 'a' in x)
如果您的 Series
中没有任何 NaN 值,这将正常工作,但如果有,您可以使用:
arr.apply(lambda x: 'a' in x if x is not np.nan else x)
这比使用 Series.str
快得多。
基准:
%%timeit
arr.str.join(sep='~').str.contains('a')
参加:249 µs ± 4.83 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%%timeit
arr.apply(lambda x: 'a' in x)
需要:70.1 µs ± 1.68 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%%timeit
arr.apply(lambda x: 'a' in x if x is not np.nan else x)
需要:69 µs ± 1.6 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)