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

标签 python python-3.x datatable py-datatable

我无法执行标准 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/

相关文章:

linq - 使用 LINQ 从另一个表更新 DataTable

python - 使用 mod_wsgi 部署具有域和子域的 django 应用程序

python - 使用 Python 库打包 C 库

python - 64位Python可以连接32位MS访问驱动程序吗?

jquery - 数据表中的下拉列表

mysql - 如何使用 DataRow 更新数据库?

python - 如何在 opencv-python 中将文本打印到框架

python - 如何在python中使用print语句测试文件写入

python - 如何在直方图上设置轴并交换 x 轴和 y 轴?

python - 使用 Python 3 将大型 CSV 文件转换为 excel