python - Pandas - 过滤和正则表达式搜索 DataFrame 的索引

标签 python regex pandas

我有一个 DataFrame,其中的列是 MultiIndex,索引是名称列表,即 index=['Andrew', 'Bob', 'Calvin',...]

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

我用正则表达式参数查看了 df.filter(),但它失败了,我得到:

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

或:

df.filter(regex=('a',1)
TypeError: first argument must be string or compiled pattern

我已经尝试过其他方法,例如传递 re.compile('a') 无济于事。

最佳答案

看来我的 filter 问题的一部分是我使用的是过时版本的 pandas。更新后,我不再收到 TypeError。经过一番尝试后,看起来我可以使用 filter 来满足我的需要。这是我的发现。

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

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

关于python - Pandas - 过滤和正则表达式搜索 DataFrame 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35638377/

相关文章:

python - 如何解决使用 Python 解码和打印希腊字符的困难?

javascript - 密码正则表达式来阻止方括号和空格?

python - django 管理站点 - 过滤用户可用的对象

python - 根据变量类别的计数绘制数据集

java - 正则表达式获取逗号分隔值中的第 n 个值

ruby - 如何在 Ruby 的子字符串中拆分 CamelCase 字符串?

python - dfply:变异字符串列:TypeError

python - 生成pandas中的所有组合

python - 如何在 Pandas 的 groupby 之后获取列的计数百分比

python - Pandas to_datetime 意外更改年份