Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Pandas-filter和regex搜索数据帧的索引_Python_Regex_Pandas - Fatal编程技术网

Python Pandas-filter和regex搜索数据帧的索引

Python Pandas-filter和regex搜索数据帧的索引,python,regex,pandas,Python,Regex,Pandas,我有一个数据框架,其中列是多索引的,索引是一个名称列表,即index=['Andrew','Bob','Calvin',…] 我想创建一个函数来返回数据帧中所有使用名称“Bob”或可能以字母“a”开头或以小写字母开头的行。如何做到这一点 我使用regex参数查看了df.filter(),但是失败了,我得到: df.filter(regex='a') TypeError: expected string or buffer 或: 我尝试过其他方法,比如传递re.compile('a'),但没有效

我有一个数据框架,其中列是多索引的,索引是一个名称列表,即
index=['Andrew','Bob','Calvin',…]

我想创建一个函数来返回数据帧中所有使用名称“Bob”或可能以字母“a”开头或以小写字母开头的行。如何做到这一点

我使用regex参数查看了
df.filter()
,但是失败了,我得到:

df.filter(regex='a')
TypeError: expected string or buffer
或:


我尝试过其他方法,比如传递
re.compile('a')
,但没有效果。

也许可以通过使用列表理解和.ix尝试不同的方法:

import pandas as pd

df = pd.DataFrame(range(4),index=['Andrew', 'Bob', 'Calvin','yosef'])

df.ix[[x for x in df.index if x=='Bob']]

df.ix[[x for x in df.index if x[0]=='A']]

df.ix[[x for x in df.index if x.islower()]]

因此,我使用
过滤器的部分问题似乎是因为我使用了一个过时的pandas版本。更新后,我不再得到
类型错误
。在玩了一些游戏之后,我似乎可以使用
过滤器来满足我的需要。这是我发现的

只需设置
df.filter(regex='string')
即可返回与regex匹配的列。这看起来与df.filter(regex='string',axis=1)的作用相同。


要搜索索引,我只需要做
df.filter(regex='string',axis=0)

同样的问题,没有什么新的。在这个示例中,他们正在过滤列,索引默认为[0,1,2,3]。我的索引是一个名字列表。谢谢。这回答了我的问题。如果有人使用
df.filter
,你知道吗?很高兴看到一些例子。这很好,但是我需要单独处理搜索列的操作,这会降低代码的简洁性
import pandas as pd

df = pd.DataFrame(range(4),index=['Andrew', 'Bob', 'Calvin','yosef'])

df.ix[[x for x in df.index if x=='Bob']]

df.ix[[x for x in df.index if x[0]=='A']]

df.ix[[x for x in df.index if x.islower()]]