Pandas Dataframe 到 Apache Beam PCollection 的转换问题

Pandas Dataframe to Apache Beam PCollection conversion problem

我正在尝试将 pandas DataFrame 转换为来自 Apache Beam 的 PCollection。 不幸的是,当我使用 to_pcollection() 函数时,出现以下错误:

AttributeError: 'DataFrame' object has no attribute '_expr'

有谁知道怎么解决的吗? 我正在使用 pandas=1.1.4、beam=2.25.0 和 Python 3.6.9.

当我在 Beam 中使用“本地”Pandas 数据框而不是 to_dataframe 创建的数据框时,我遇到了这个问题。我怀疑由 Beam 创建的数据帧包装或子类化了一个 Pandas 数据帧,它具有原生 Pandas 数据帧所没有的新属性(如 _expr)。

真正的答案是知道如何使用apache_beam.dataframe.convert.to_dataframe,但我不知道如何正确设置代理对象(我稍后尝试使用to_pcollection时出现单例错误) .因此,由于我无法获得在 2.25.0 中工作的“正确”方式(我是 Beam 和 Pandas 的新手——并且不知道代理对象是如何工作的——所以对这一切持谨慎态度盐),我使用这个解决方法:

class SomeDoFn(beam.DoFn):
    def process(self, pair): # pair is a key/value tuple
        df = pd.DataFrame(pair[1]) # just the array of values

        ## do something with the dataframe
        ...

        records = df.to_dict('records')

        # return a tuple with the same shape as the one we received
        return [(rec["key"], rec) for rec in records]

我用这样的方式调用:

rows = (
    pcoll
    | beam.ParDo(SomeDoFn())
)

我希望其他人会给你比这个解决方法更好的答案。

to_pcollection 只打算应用于 Beam 的延迟数据帧,但从这个角度来看,它应该可以工作是有道理的,但如何手动操作并不明显。 https://github.com/apache/beam/pull/14170 应该可以解决这个问题。