Docs Menu
Docs Home
/ / /
PyMongoArrow

데이터 유형

이 페이지의 내용

  • 임베디드 배열 고려 사항
  • 확장 유형
  • Null 값 및 Pandas DataFrames로 변환
  • 중첩된 확장 유형

PyMongoArrow는 대부분의 BSON types를 지원합니다. 화살표와 폴라가 목록과 구조체에 대해 최고 수준의 지원을 제공하기 때문에 여기에는 내장된 배열과 문서가 포함됩니다.

추가 유형에 대한 지원은 후속 릴리스에서 추가될 예정입니다.

BSON types에 대한 자세한 내용은 BSON 사양을 참조하세요.

BSON 유형
유형 식별자
문자열
py.str, 인스턴스의 pyarrow.string
embeddedDocument
py.dict및 인스턴스 pyarrow.struct
임베디드 배열
인스턴스 pyarrow.list_
ObjectId
py.bytes, bson.ObjectId, pymongoarrow.types.ObjectIdType 인스턴스 , pymongoarrow.pandas_types.PandasObjectId인스턴스
Decimal128
bson.Decimal128pymongoarrow.types.Decimal128Type 인스턴스, pymongoarrow.pandas_types.PandasDecimal128인스턴스
부울
~pyarrow.bool_ 의 인스턴스, ~py.bool
64비트 이진 부동 소수점
py.float, 인스턴스의 pyarrow.float64
32비트 정수
인스턴스 pyarrow.int32
64비트 정수
~py.int, bson.int64.Int64, pyarrow.int64의 인스턴스
UTC 날짜/시간
ms 확인이 ~pyarrow.timestamp 의 인스턴스인 py.datetime.datetime입니다.
이진 데이터
bson.Binary, pymongoarrow.types.BinaryType 의 인스턴스, pymongoarrow.pandas_types.PandasBinary 의 인스턴스.
JavaScript 코드
bson.Codepymongoarrow.types.CodeType 인스턴스, pymongoarrow.pandas_types.PandasCode인스턴스

참고

PyMongoArrow는 리틀 엔디안 시스템에서만 Decimal128 을 지원합니다. 빅 엔디안 시스템에서는 대신 null 을(를) 사용합니다.

유형 식별자를 사용하여 pymongoarrow.api.Schema 선언 시 필드가 특정 유형임을 지정합니다. 예를 들어 데이터에 32비트 정수 및 UTC 날짜/시간 유형을 포함하는 f1f2 필드가 있고 ObjectId_id 이 있는 경우 다음과 같이 스키마를 정의할 수 있습니다.

schema = Schema({
'_id': ObjectId,
'f1': pyarrow.int32(),
'f2': pyarrow.timestamp('ms')
})

스키마에서 지원되지 않는 데이터 유형으로 인해 필드와 해당 데이터 유형을 식별하는 ValueError 가 발생합니다.

포함된 배열에 사용되는 스키마는 배열 요소의 유형을 지정하기 위해 pyarrow.list_() 유형을 사용해야 합니다. 예를 들면 다음과 같습니다.

from pyarrow import list_, float64
schema = Schema({'_id': ObjectId,
'location': {'coordinates': list_(float64())}
})

PyMongoArrow는 ObjectId, Decimal128, Binary dataJavaScript code 유형을 PyArrow 및 Pandas의 확장 유형으로 구현합니다. 화살표 테이블의 경우 이러한 유형의 값에는 pymongoarrow.types.ObjectIdType 과 같은 적절한 pymongoarrow 확장자 유형이 있습니다. .as_py() 메서드를 사용하거나 테이블에서 .to_pylist() 을(를) 호출하여 적절한 bson Python 객체를 얻을 수 있습니다.

>>> from pymongo import MongoClient
>>> from bson import ObjectId
>>> from pymongoarrow.api import find_arrow_all
>>> client = MongoClient()
>>> coll = client.test.test
>>> coll.insert_many([{"_id": ObjectId(), "foo": 100}, {"_id": ObjectId(), "foo": 200}])
<pymongo.results.InsertManyResult at 0x1080a72b0>
>>> table = find_arrow_all(coll, {})
>>> table
pyarrow.Table
_id: extension<arrow.py_extension_type<ObjectIdType>>
foo: int32
----
_id: [[64408B0D5AC9E208AF220142,64408B0D5AC9E208AF220143]]
foo: [[100,200]]
>>> table["_id"][0]
<pyarrow.ObjectIdScalar: ObjectId('64408b0d5ac9e208af220142')>
>>> table["_id"][0].as_py()
ObjectId('64408b0d5ac9e208af220142')
>>> table.to_pylist()
[{'_id': ObjectId('64408b0d5ac9e208af220142'), 'foo': 100},
{'_id': ObjectId('64408b0d5ac9e208af220143'), 'foo': 200}]

pandas로 변환할 때 확장 유형 열에는 pymongoarrow.pandas_types.PandasDecimal128 과 같은 적절한 pymongoarrow 확장 유형이 있습니다. 데이터 프레임의 요소 값이 적절한 bson 유형입니다.

>>> from pymongo import MongoClient
>>> from bson import Decimal128
>>> from pymongoarrow.api import find_pandas_all
>>> client = MongoClient()
>>> coll = client.test.test
>>> coll.insert_many([{"foo": Decimal128("0.1")}, {"foo": Decimal128("0.1")}])
<pymongo.results.InsertManyResult at 0x1080a72b0>
>>> df = find_pandas_all(coll, {})
>>> df
_id foo
0 64408bf65ac9e208af220144 0.1
1 64408bf65ac9e208af220145 0.1
>>> df["foo"].dtype
<pymongoarrow.pandas_types.PandasDecimal128 at 0x11fe0ae90>
>>> df["foo"][0]
Decimal128('0.1')
>>> df["_id"][0]
ObjectId('64408bf65ac9e208af220144')

폴라리스는 확장 유형을 지원하지 않습니다.

화살표 및 폴라에서 모든 배열은 null을 허용합니다. Pandas에는 Int64 과 같은 실험적인 null 허용 데이터 유형이 있습니다. 다음 Apache 문서 코드에서null 허용 dtypes를 사용하여 pandas DataFrame을 만들도록 Arrow에 지시할 수 있습니다.

>>> dtype_mapping = {
... pa.int8(): pd.Int8Dtype(),
... pa.int16(): pd.Int16Dtype(),
... pa.int32(): pd.Int32Dtype(),
... pa.int64(): pd.Int64Dtype(),
... pa.uint8(): pd.UInt8Dtype(),
... pa.uint16(): pd.UInt16Dtype(),
... pa.uint32(): pd.UInt32Dtype(),
... pa.uint64(): pd.UInt64Dtype(),
... pa.bool_(): pd.BooleanDtype(),
... pa.float32(): pd.Float32Dtype(),
... pa.float64(): pd.Float64Dtype(),
... pa.string(): pd.StringDtype(),
... }
... df = arrow_table.to_pandas(
... types_mapper=dtype_mapping.get, split_blocks=True, self_destruct=True
... )
... del arrow_table

pa.string() 에 대한 변환을 정의하면 객체가 아닌 화살표 문자열도 NumPy 문자열로 변환됩니다.

보류 중인 화살표-179 ObjectId중첩된 문서에 나타나는 확장자 유형(예: )은 해당 PyMongoArrow 확장자 유형으로 변환되지 않고 대신 원시 화살표 유형인 을FixedSizeBinaryType(fixed_size_binary[12]) 갖습니다.

이러한 값은 그대로 사용하거나 _id = out['nested'][0]['_id'].cast(ObjectIdType()) 과 같이 원하는 확장 유형으로 개별적으로 변환할 수 있습니다.

돌아가기

PyMongo와 비교하기