逐行构建pyarrow表的最快方法

Jos*_* W. 8 python apache-arrow pyarrow

我有一个很大的字典,我想遍历它来构建一个 pyarrow 表。字典的值是不同类型的元组,需要解包并存储在最终 pyarrow 表中的单独列中。我确实提前知道架构。键还需要存储为列。我在下面有一种方法可以逐行构建表格 - 还有另一种更快的方法吗?对于上下文,我想将一个大字典解析为一个 pyarrow 表以写出到镶木地板文件中。RAM 使用比 CPU 时间更重要。我不想下降到箭头 C++ API。

import pyarrow as pa
import random
import string 
import time

large_dict = dict()

for i in range(int(1e6)):
    large_dict[i] = (random.randint(0, 5), random.choice(string.ascii_letters))


schema = pa.schema({
        "key"  : pa.uint32(),
        "col1" : pa.uint8(),
        "col2" : pa.string()
   })

start = time.time()

tables = []
for key, item in large_dict.items():
    val1, val2 = item
    tables.append(
            pa.Table.from_pydict({
                    "key"  : [key],
                    "col1" : [val1],
                    "col2" : [val2]
                }, schema = schema)

            )

table = pa.concat_tables(tables)
end = time.time()
print(end - start) # 22.6 seconds on my machine

Run Code Online (Sandbox Code Playgroud)

Olu*_*ule 7

由于模式是提前知道的,您可以为每一列创建一个列表,并构建一个列名和列值对的字典。

%%timeit -r 10
import pyarrow as pa
import random
import string 
import time

large_dict = dict()

for i in range(int(1e6)):
    large_dict[i] = (random.randint(0, 5), random.choice(string.ascii_letters))


schema = pa.schema({
        "key"  : pa.uint32(),
        "col1" : pa.uint8(),
        "col2" : pa.string()
  })

keys = []
val1 = []
val2 = []
for k, (v1, v2) in large_dict.items():
  keys.append(k)
  val1.append(v1)
  val2.append(v2)

table = pa.Table.from_pydict(
    dict(
        zip(schema.names, (keys, val1, val2))
    ),
    schema=schema
)
Run Code Online (Sandbox Code Playgroud)

每个循环 2.92 s ± 236 ms(平均值 ± 标准偏差,10 次运行,每次 1 次循环)