gpt4 book ai didi

python - py-datatable 'in' 运算符?

转载 作者:行者123 更新时间:2023-12-03 16:02:08 25 4
gpt4 key购买 nike

我无法执行标准 in使用预定义的项目列表进行操作。我想做这样的事情:

# Construct a simple example frame
from datatable import *
df = Frame(V1=['A','B','C','D'], V2=[1,2,3,4])

# Filter frame to a list of items (THIS DOES NOT WORK)
items = ['A','B']
df[f.V1 in items,:]


此示例导致错误:
TypeError: A boolean value cannot be used as a row selector
不幸的是, in 似乎没有内置对象。操作。我想使用 %in% 之类的东西R 语言原生的运算符。 有什么方法可以在python中完成这个吗?

我可以通过使用多个“等于”运算符来采用这种方法,但是当您要考虑大量项目时,这很不方便:
df[(f.V1 == 'A') | (f.V1 == 'B'),:]

数据表 0.10.1
python 3.6

最佳答案

你也可以试试这个:

首先导入所有必要的包,

import datatable as dt
from datatable import by,f,count
import functools
import operator

创建示例数据表:
DT = dt.Frame(V1=['A','B','C','D','E','B','A'], V2=[1,2,3,4,5,6,7])

列出要在观察中过滤的值,在您的情况下是
sel_obs = ['A','B']

现在使用 funtools 和 operator 模块创建过滤器表达式,
filter_rows = functools.reduce(operator.or_,(f.V1==obs for obs in sel_obs))

最后在数据表上应用上面创建的过滤器
DT[fil_rows,:]

它的输出为-
Out[6]: 
| V1 V2
-- + -- --
0 | A 1
1 | B 2
2 | B 6
3 | A 7

[4 rows x 2 columns]

您可以与运算符(operator)一起玩来进行不同类型的过滤。

@sammyweemy 的解决方案也应该有效。

关于python - py-datatable 'in' 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62378782/

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