python - 在 Pandas 数据框中查找嵌套列

标签 python python-3.x pandas pyarrow

我有一个包含许多列(压缩)JSON 格式的大型数据集。我正在尝试将其转换为 Parquet 以进行后续处理。某些列具有嵌套结构。现在我想忽略这个结构,只是将这些列作为(JSON)字符串写出来。

所以对于我确定的列,我正在做:

df[column] = df[column].astype(str)

但是,我不确定哪些列是嵌套的,哪些不是。当我用 Parquet 书写时,我看到以下消息:
<stack trace redacted> 

  File "pyarrow/_parquet.pyx", line 1375, in pyarrow._parquet.ParquetWriter.write_table
  File "pyarrow/error.pxi", line 78, in pyarrow.lib.check_status
pyarrow.lib.ArrowInvalid: Nested column branch had multiple children: struct<coordinates: list<item: double>, type: string>

这表明我未能将我的一列从嵌套对象转换为字符串。但应该归咎于哪个专栏?我怎么知道?

当我打印 .dtypes在我的 Pandas 数据帧中,我无法区分字符串和嵌套值,因为两者都显示为 object .

编辑:该错误通过显示结构详细信息提示了嵌套列,但这非常耗时调试。此外,它只打印第一个错误,如果您有多个嵌套列,这可能会很烦人

最佳答案

将嵌套结构转换为字符串

如果我正确理解您的问题,您想在 df 中序列化那些嵌套的 Python 对象(列表、字典) JSON 字符串并保持其他元素不变。最好编写自己的类型转换方法:

def json_serializer(obj):
    if isinstance(obj, [list, dict]): # please add other types that you considered as nested structure to the type list
        return json.dumps(obj)
    return obj

df = df.applymap(json_serializer)

如果数据框很大,请使用 astype(str)会更快。
nested_cols = []
for c in df:
    if any(isinstance(obj, [list, dict]) for obj in df[c]):
        nested_cols.append(c)

for c in nested_cols:
    df[c] = df[c].astype(str) # this convert every element in the column independent of their types

由于对 any(...) 的调用中的短路评估,这种方法具有性能优势。 .一旦命中列中的第一个嵌套对象,它将立即返回,并且不会浪费时间检查其余对象。如果任何“Dtype Introspection”方法适合您的数据,使用它会更快。

检查最新版本的pyarrow

我假设那些嵌套结构需要转换为字符串只是因为它们会导致 pyarrow.parquet.write_table 中的错误。 .
也许你根本不需要转换它,因为pyarrow中处理嵌套列的问题已经reportedly solved recently (2020 年 3 月 29 日,版本 0.17.0)。
但是支持可能有问题,下active discussion .

关于python - 在 Pandas 数据框中查找嵌套列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61196119/

相关文章:

Python App Engine 全文搜索 > 空搜索返回搜索的所有文档。索引

python - pyhamcrest修改 "got"描述

python - 用于桌面应用程序的 Django ORM

python-3.x - key 错误 : 'axes.color_cycle is not a valid rc parameter (see rcParams.keys() for a list of valid parameters)'

Python 3.5 字符串格式 : How to add a thousands-separator and also right justify?

python - 比较Python中的浮点值

python - 如何过滤pandas数据框?

python - ThreadPoolExecutor 未定义 [python3]

Python3查找2个列表中有多少差异才能相等

python - 列(索引格式)到数据框?