Преобразованный файл стрелки apache из фрейма данных дает нулевое значение при чтении с помощью arrow.js - PullRequest
5 голосов
/ 10 октября 2019

Я преобразовал один пример данных в .arrow файл, используя pyarrow

import numpy as np
import pandas as pd
import pyarrow as pa

df = pd.DataFrame({"a": [10, 2, 3]})
df['a'] = pd.to_numeric(df['a'],errors='coerce')
table = pa.Table.from_pandas(df)
writer = pa.RecordBatchFileWriter('test.arrow', table.schema)
writer.write_table(table)
writer.close()

Это создает файл test.arrow

df.info()
    <class 'pandas.core.frame.DataFrame'>
    RangeIndex: 3 entries, 0 to 2
    Data columns (total 1 columns):
    a    3 non-null int64
    dtypes: int64(1)
    memory usage: 104.0 bytes

Затем в NodeJS я загружаю файл сarrowJS. https://arrow.apache.org/docs/js/

const fs = require('fs');
const arrow = require('apache-arrow');

const data = fs.readFileSync('test.arrow');
const table = arrow.Table.from(data);

console.log(table.schema.fields.map(f => f.name));
console.log(table.count());
console.log(table.get(0));

Это печатается как

[ 'a' ]
0
null

Я ожидал, что эта таблица будет иметь длину 3, а table.get(0) дает первую строку вместо null.

Это таблица выглядит как console.log(table._schema)

[ Int_ [Int] { isSigned: true, bitWidth: 16 } ]
Schema {
  fields:
   [ Field { name: 'a', type: [Int_], nullable: true, metadata: Map {} } ],
  metadata:
   Map {
     'pandas' => '{"index_columns": [{"kind": "range", "name": null, "start": 0, "stop": 5, "step": 1}], "column_indexes": [{"name": null, "field_name": null, "pandas_type": "unicode", "numpy_type": "object", "metadata": {"encoding": "UTF-8"}}], "columns": [{"name": "a", "field_name": "a", "pandas_type": "int16", "numpy_type": "int16", "metadata": null}], "creator": {"library": "pyarrow", "version": "0.15.0"}, "pandas_version": "0.22.0"}' },
  dictionaries: Map {} }

Есть идеи, почему она не получает данные, как ожидалось?

1 Ответ

2 голосов
/ 17 октября 2019

Это связано с изменением формата в Стрелке 0.15, как , упомянутое Уэсом в Apache JIRA. Это означает, что все библиотеки Arrow, а не только PyArrow, обнаружат эту проблему при отправке файлов IPC в более старые версии Arrow. Исправление состоит в том, чтобы обновить ArrowJS до 0.15.0, чтобы вы могли совершать обходы между другими библиотеками Arrow и библиотекой JS. Если по какой-либо причине вы не можете выполнить обновление, вместо этого вы можете использовать один из следующих способов:

Передать use_legacy_format=True в качестве kwarg на RecordBatchFileWriter:

with pa.RecordBatchFileWriter('file.arrow', table.schema, use_legacy_format=True) as writer:
    writer.write_table(table)

Установить средупеременная ARROW_PRE_0_15_IPC_FORMAT до 1:

$ export ARROW_PRE_0_15_IPC_FORMAT = 1
$ python
>>> import pyarrow as pa
>>> table = pa.Table.from_pydict( {"a": [1, 2, 3], "b": [4, 5, 6]} )
>>> with pa.RecordBatchFileWriter('file.arrow', table.schema) as writer:
...   writer.write_table(table)
...

или понижение PyArrow до 0.14.x:

$ conda install -c conda-forge pyarrow=0.14.1
...