[英]find string in pandas series python
I cannot figure out how to find a string in a pandas series:我不知道如何在熊猫系列中找到一个字符串:
mydata = np.array(['ab','ac','ad','ae'])
myserie = pd.Series(mydata) # this is because I don't know how to initialise a series directly ... :(
I am looking for the index of the string ac
.我正在寻找字符串ac
的索引。
I have tried myserie.str.find('ac')
but that returns我试过myserie.str.find('ac')
但它返回
Out[270]:
0 -1
1 -1
2 -1
3 -1
dtype: int64
which has two problems: I want only the index of the ac
string (which out be 1), and well, it doesn't spot it.... what am I doing wrong?这有两个问题:我只想要ac
字符串的索引(它是 1),而且它没有发现它......我做错了什么? what would work?什么会起作用?
Use Series.str.contains
for test substring:使用Series.str.contains
测试子串:
idx = myserie.index[myserie.str.contains('ac')]
If need exact match use ==
or Series.eq
:如果需要精确匹配使用==
或Series.eq
:
idx = myserie.index[myserie.eq('ac')]
print (idx)
Int64Index([1], dtype='int64')
For scalar use next
with iter
trick for return value also if no match:对于标量,如果没有匹配,也可以使用带有iter
技巧的next
返回值:
out = next(iter(idx), 'no match')
print (out)
1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.