【问题标题】:PyArrow Table: Filter rowsPyArrow 表:过滤行
【发布时间】:2022-03-04 18:19:16
【问题描述】:

我有一个来自 Plasma DataStore 的 RecordBatch,我可以将其读入 pyarrow.RecordBatchpyarrow.Table。我现在试图在将行转换为熊猫之前过滤掉行(to_pandas)。

有没有办法在pyarrow.Table 上使用来自新数据集 API(您可以在 ParquetDataset 上使用)中的 filter 方法?这将允许我给我们一个这样的过滤器:

[[('date', '=', '2020-01-01')]]

查看源代码pyarrow.Tablepyarrow.RecordBatch 似乎都有过滤功能,但至少RecordBatch 需要布尔掩码。

这可能吗?原因是数据集包含许多不是零拷贝的字符串(和/或类别),因此运行to_pandas 实际上会引入显着的延迟,而我只在寻找大约 20% 的数据集。

问候,
尼克拉斯

【问题讨论】:

标签: python pandas pyarrow


【解决方案1】:

这现在是可能的:

import pyarrow as pa

my_table = pa.Table.from_arrays(
    [pa.array(['foo', 'bar', 'foo'], pa.string())],
    names=['col1']
)

filtered_table = my_table.filter(pa.compute.equal(my_table['col1'], 'foo'))

【讨论】:

  • 太棒了!这很有帮助。您知道是否还可以过滤同一列上的条件联合?
  • 我现在正在这样做顺便说一句:``` def filter_options(table: pa.Table, filter_values: Iterable, colname: str): tables = [] for filter_val in filter_values: tables.append( table.filter(pa.compute.equal(table[colname], filter_val))) return pa.concat_tables(tables) ``` 但我不确定这将如何表现 w.r.t 内存?会制作新表格,还是会调整视图?
  • pa.compute.filter 的文档没有说明它在内存方面的行为。我怀疑它返回一个视图,因为它没有接收内存池作为参数。 PS:如果您担心性能,您应该考虑在您的情况下使用pa.compute.is_in,而不是 pa.compute.eqal`
  • 这是最好的例子。但是,这仅显示单个列的“where”子句;有没有一种简单的方法可以在两列上执行此操作?
【解决方案2】:

上面的问题相当于

WHERE date = '2020-01-01'

值得一提的是,PyArrow 函数的范围可用于在https://arrow.apache.org/docs/python/api/compute.html#containment-tests 上提供更广泛的选择条件

# import pyarrow.compute  as pc 
# WHERE test_table.name LIKE 'T%'
filtered_table = test_table.filter(pc.match_like(test_table["name"],"T%"))

作为过滤器返回一个表结构,您可以一个接一个地链接过滤器。

# WHERE test_table.name LIKE 'T%' AND test_table.date_updated = '2020-01-01'
filtered_table = test_table.filter(
    pc.match_like(test_table["name"],"T%")
).(
    pc.equal(test_table["date_updated"], "2020-01-01")
)

【讨论】:

  • 我无法使用这种方法。我认为您需要在链中使用.filter 以避免语法错误。当我确实让链条工作时,我最终会遇到错误pyarrow.lib.ArrowInvalid: Filter inputs must all be the same length
猜你喜欢
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 2022-08-10
  • 2019-01-06
  • 1970-01-01
  • 1970-01-01
  • 2020-01-16
  • 1970-01-01
相关资源
最近更新 更多