繁体   English   中英

在熊猫系列python中查找字符串

[英]find string in pandas series python

我不知道如何在熊猫系列中找到一个字符串:

mydata = np.array(['ab','ac','ad','ae'])
myserie = pd.Series(mydata) # this is because I don't know how to initialise a series directly ... :(

我正在寻找字符串ac的索引。

我试过myserie.str.find('ac')但它返回

Out[270]: 
0   -1
1   -1
2   -1
3   -1
dtype: int64

这有两个问题:我只想要ac字符串的索引(它是 1),而且它没有发现它......我做错了什么? 什么会起作用?

使用Series.str.contains测试子串:

idx = myserie.index[myserie.str.contains('ac')]

如果需要精确匹配使用==Series.eq

idx = myserie.index[myserie.eq('ac')]
print (idx)
Int64Index([1], dtype='int64')

对于标量,如果没有匹配,也可以使用带有iter技巧的next返回值:

out = next(iter(idx), 'no match')
print (out)
1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM