gpt4 book ai didi

python - 在 Pandas 的查询中使用动态列表

转载 作者:行者123 更新时间:2023-11-28 21:20:07 25 4
gpt4 key购买 nike

举例来说,我有几个列对不同类型的费率进行编码(“年费率”“1/2 年费率”、 ETC。)。我想在我的数据框上使用 query 来查找这些速率中任何 高于 1 的条目。

首先,我找到了我想在查询中使用的列:

cols = [x for ix, x in enumerate(df.columns) if 'rate' in x]

例如,cols 包含:

["annual rate", "1/2 annual rate", "monthly rate"]

然后我想做类似的事情:

df.query('any of my cols > 1')

如何为query设置格式?

最佳答案

query 执行 Python expression 的完整解析(有一些限制,例如,您不能使用 lambda 表达式或三元 if/else 表达式)。这意味着您在查询字符串中引用的任何列必须是有效的 Python 标识符(“变量名称”的更正式的词)。检查这一点的一种方法是使用潜伏在 tokenize 模块中的 Name 模式:

In [156]: tokenize.Name
Out[156]: '[a-zA-Z_]\\w*'

In [157]: def isidentifier(x):
.....: return re.match(tokenize.Name, x) is not None
.....:

In [158]: isidentifier('adsf')
Out[158]: True

In [159]: isidentifier('1adsf')
Out[159]: False

现在因为你的列名有空格,每个由空格分隔的单词将被评估为单独的标识符,所以你会有类似的东西

df.query("annual rate > 1")

这是无效的 Python 语法。尝试在 Python 解释器中输入 annual rate,你会得到一个 SyntaxError 异常。

重要信息:将您的列重命名为有效的变量名称。除非您的列遵循某种结构,否则您将无法以编程方式(至少,轻松地)执行此操作。在你的情况下你可以做

In [166]: cols
Out[166]: ['annual rate', '1/2 annual rate', 'monthly rate']

In [167]: list(map(lambda x: '_'.join(x.split()).replace('1/2', 'half'), cols))
Out[167]: ['annual_rate', 'half_annual_rate', 'monthly_rate']

然后您可以像@acushner 的示例一样格式化查询字符串

In [173]: newcols
Out[173]: ['annual_rate', 'half_annual_rate', 'monthly_rate']

In [174]: ' or '.join('%s > 1' % c for c in newcols)
Out[174]: 'annual_rate > 1 or half_annual_rate > 1 or monthly_rate > 1'

注意:您实际上不需要在此处使用query:

In [180]: df = DataFrame(randn(10, 3), columns=cols)

In [181]: df
Out[181]:
annual rate 1/2 annual rate monthly rate
0 -0.6980 0.6322 2.5695
1 -0.1413 -0.3285 -0.9856
2 0.8189 0.7166 -1.4302
3 1.3300 -0.9596 -0.8934
4 -1.7545 -0.9635 2.8515
5 -1.1389 0.1055 0.5423
6 0.2788 -1.3973 -0.9073
7 -1.8570 1.3781 0.0501
8 -0.6842 -0.2012 -0.5083
9 -0.3270 -1.5280 0.2251

[10 rows x 3 columns]

In [182]: df.gt(1).any(1)
Out[182]:
0 True
1 False
2 False
3 True
4 True
5 False
6 False
7 True
8 False
9 False
dtype: bool

In [183]: df[df.gt(1).any(1)]
Out[183]:
annual rate 1/2 annual rate monthly rate
0 -0.6980 0.6322 2.5695
3 1.3300 -0.9596 -0.8934
4 -1.7545 -0.9635 2.8515
7 -1.8570 1.3781 0.0501

[4 rows x 3 columns]

正如@Jeff 在评论中指出的那样,您可以引用非标识符列名称,尽管方式很笨拙:

pd.eval('df[df["annual rate"]>0]')

如果您想挽救小猫的生命,我不建议您编写这样的代码。

关于python - 在 Pandas 的查询中使用动态列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23342532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com