通过索引中的部分字符串匹配选择行 [英] Select rows by partial string match in index

查看:36
本文介绍了通过索引中的部分字符串匹配选择行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个这样的系列:

ds = Series({'wikipedia':10,'wikimedia':22,'wikitravel':33,'google':40})

google        40
wikimedia     22
wikipedia     10
wikitravel    33
dtype: int64

我想选择wiki"是索引标签(部分字符串标签)一部分的行.

I would like to select the rows where 'wiki' is a part of the index label (a partial string label).

暂时我尝试了

ds[ds.index.map(lambda x: 'wiki' in x)]

wikimedia     22
wikipedia     10
wikitravel    33
Name: site, dtype: int64

它完成了这项工作,但不知何故,索引会像列所具有的那样为包含"而哭泣...

and it does the job, but somehow the index cries for 'contains' just like what the columns have...

有没有更好的方法来做到这一点?

Any better way to do that?

推荐答案

使用 loc 可能有点厚颜无耻:

A somewhat cheeky way could be to use loc:

In [11]: ds.loc['wiki': 'wikj']
Out[11]:
wikimedia     22
wikipedia     10
wikitravel    33
dtype: int64

这本质上等同于 ds[ds.index.map(lambda s: s.startswith('wiki'))].

To do contains,正如@DSM 建议的那样,写成这样可能更好:

To do contains, as @DSM suggests, it's probably nicer to write as:

ds[['wiki' in s for s in ds.index]]

这篇关于通过索引中的部分字符串匹配选择行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆