pandas_compat.py 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. import ast
  18. from collections.abc import Sequence
  19. from concurrent import futures
  20. # import threading submodule upfront to avoid partially initialized
  21. # module bug (ARROW-11983)
  22. import concurrent.futures.thread # noqa
  23. from copy import deepcopy
  24. from itertools import zip_longest
  25. import json
  26. import operator
  27. import re
  28. import warnings
  29. import numpy as np
  30. import pyarrow as pa
  31. from pyarrow.lib import _pandas_api, builtin_pickle, frombytes # noqa
  32. _logical_type_map = {}
  33. def get_logical_type_map():
  34. global _logical_type_map
  35. if not _logical_type_map:
  36. _logical_type_map.update({
  37. pa.lib.Type_NA: 'empty',
  38. pa.lib.Type_BOOL: 'bool',
  39. pa.lib.Type_INT8: 'int8',
  40. pa.lib.Type_INT16: 'int16',
  41. pa.lib.Type_INT32: 'int32',
  42. pa.lib.Type_INT64: 'int64',
  43. pa.lib.Type_UINT8: 'uint8',
  44. pa.lib.Type_UINT16: 'uint16',
  45. pa.lib.Type_UINT32: 'uint32',
  46. pa.lib.Type_UINT64: 'uint64',
  47. pa.lib.Type_HALF_FLOAT: 'float16',
  48. pa.lib.Type_FLOAT: 'float32',
  49. pa.lib.Type_DOUBLE: 'float64',
  50. pa.lib.Type_DATE32: 'date',
  51. pa.lib.Type_DATE64: 'date',
  52. pa.lib.Type_TIME32: 'time',
  53. pa.lib.Type_TIME64: 'time',
  54. pa.lib.Type_BINARY: 'bytes',
  55. pa.lib.Type_FIXED_SIZE_BINARY: 'bytes',
  56. pa.lib.Type_STRING: 'unicode',
  57. })
  58. return _logical_type_map
  59. def get_logical_type(arrow_type):
  60. logical_type_map = get_logical_type_map()
  61. try:
  62. return logical_type_map[arrow_type.id]
  63. except KeyError:
  64. if isinstance(arrow_type, pa.lib.DictionaryType):
  65. return 'categorical'
  66. elif isinstance(arrow_type, pa.lib.ListType):
  67. return 'list[{}]'.format(get_logical_type(arrow_type.value_type))
  68. elif isinstance(arrow_type, pa.lib.TimestampType):
  69. return 'datetimetz' if arrow_type.tz is not None else 'datetime'
  70. elif isinstance(arrow_type, pa.lib.Decimal128Type):
  71. return 'decimal'
  72. return 'object'
  73. _numpy_logical_type_map = {
  74. np.bool_: 'bool',
  75. np.int8: 'int8',
  76. np.int16: 'int16',
  77. np.int32: 'int32',
  78. np.int64: 'int64',
  79. np.uint8: 'uint8',
  80. np.uint16: 'uint16',
  81. np.uint32: 'uint32',
  82. np.uint64: 'uint64',
  83. np.float32: 'float32',
  84. np.float64: 'float64',
  85. 'datetime64[D]': 'date',
  86. np.unicode_: 'string',
  87. np.bytes_: 'bytes',
  88. }
  89. def get_logical_type_from_numpy(pandas_collection):
  90. try:
  91. return _numpy_logical_type_map[pandas_collection.dtype.type]
  92. except KeyError:
  93. if hasattr(pandas_collection.dtype, 'tz'):
  94. return 'datetimetz'
  95. # See https://github.com/pandas-dev/pandas/issues/24739
  96. if str(pandas_collection.dtype) == 'datetime64[ns]':
  97. return 'datetime64[ns]'
  98. result = _pandas_api.infer_dtype(pandas_collection)
  99. if result == 'string':
  100. return 'unicode'
  101. return result
  102. def get_extension_dtype_info(column):
  103. dtype = column.dtype
  104. if str(dtype) == 'category':
  105. cats = getattr(column, 'cat', column)
  106. assert cats is not None
  107. metadata = {
  108. 'num_categories': len(cats.categories),
  109. 'ordered': cats.ordered,
  110. }
  111. physical_dtype = str(cats.codes.dtype)
  112. elif hasattr(dtype, 'tz'):
  113. metadata = {'timezone': pa.lib.tzinfo_to_string(dtype.tz)}
  114. physical_dtype = 'datetime64[ns]'
  115. else:
  116. metadata = None
  117. physical_dtype = str(dtype)
  118. return physical_dtype, metadata
  119. def get_column_metadata(column, name, arrow_type, field_name):
  120. """Construct the metadata for a given column
  121. Parameters
  122. ----------
  123. column : pandas.Series or pandas.Index
  124. name : str
  125. arrow_type : pyarrow.DataType
  126. field_name : str
  127. Equivalent to `name` when `column` is a `Series`, otherwise if `column`
  128. is a pandas Index then `field_name` will not be the same as `name`.
  129. This is the name of the field in the arrow Table's schema.
  130. Returns
  131. -------
  132. dict
  133. """
  134. logical_type = get_logical_type(arrow_type)
  135. string_dtype, extra_metadata = get_extension_dtype_info(column)
  136. if logical_type == 'decimal':
  137. extra_metadata = {
  138. 'precision': arrow_type.precision,
  139. 'scale': arrow_type.scale,
  140. }
  141. string_dtype = 'object'
  142. if name is not None and not isinstance(name, str):
  143. raise TypeError(
  144. 'Column name must be a string. Got column {} of type {}'.format(
  145. name, type(name).__name__
  146. )
  147. )
  148. assert field_name is None or isinstance(field_name, str), \
  149. str(type(field_name))
  150. return {
  151. 'name': name,
  152. 'field_name': 'None' if field_name is None else field_name,
  153. 'pandas_type': logical_type,
  154. 'numpy_type': string_dtype,
  155. 'metadata': extra_metadata,
  156. }
  157. def construct_metadata(columns_to_convert, df, column_names, index_levels,
  158. index_descriptors, preserve_index, types):
  159. """Returns a dictionary containing enough metadata to reconstruct a pandas
  160. DataFrame as an Arrow Table, including index columns.
  161. Parameters
  162. ----------
  163. columns_to_convert : list[pd.Series]
  164. df : pandas.DataFrame
  165. index_levels : List[pd.Index]
  166. index_descriptors : List[Dict]
  167. preserve_index : bool
  168. types : List[pyarrow.DataType]
  169. Returns
  170. -------
  171. dict
  172. """
  173. num_serialized_index_levels = len([descr for descr in index_descriptors
  174. if not isinstance(descr, dict)])
  175. # Use ntypes instead of Python shorthand notation [:-len(x)] as [:-0]
  176. # behaves differently to what we want.
  177. ntypes = len(types)
  178. df_types = types[:ntypes - num_serialized_index_levels]
  179. index_types = types[ntypes - num_serialized_index_levels:]
  180. column_metadata = []
  181. for col, sanitized_name, arrow_type in zip(columns_to_convert,
  182. column_names, df_types):
  183. metadata = get_column_metadata(col, name=sanitized_name,
  184. arrow_type=arrow_type,
  185. field_name=sanitized_name)
  186. column_metadata.append(metadata)
  187. index_column_metadata = []
  188. if preserve_index is not False:
  189. for level, arrow_type, descriptor in zip(index_levels, index_types,
  190. index_descriptors):
  191. if isinstance(descriptor, dict):
  192. # The index is represented in a non-serialized fashion,
  193. # e.g. RangeIndex
  194. continue
  195. metadata = get_column_metadata(level, name=level.name,
  196. arrow_type=arrow_type,
  197. field_name=descriptor)
  198. index_column_metadata.append(metadata)
  199. column_indexes = []
  200. levels = getattr(df.columns, 'levels', [df.columns])
  201. names = getattr(df.columns, 'names', [df.columns.name])
  202. for level, name in zip(levels, names):
  203. metadata = _get_simple_index_descriptor(level, name)
  204. column_indexes.append(metadata)
  205. else:
  206. index_descriptors = index_column_metadata = column_indexes = []
  207. return {
  208. b'pandas': json.dumps({
  209. 'index_columns': index_descriptors,
  210. 'column_indexes': column_indexes,
  211. 'columns': column_metadata + index_column_metadata,
  212. 'creator': {
  213. 'library': 'pyarrow',
  214. 'version': pa.__version__
  215. },
  216. 'pandas_version': _pandas_api.version
  217. }).encode('utf8')
  218. }
  219. def _get_simple_index_descriptor(level, name):
  220. string_dtype, extra_metadata = get_extension_dtype_info(level)
  221. pandas_type = get_logical_type_from_numpy(level)
  222. if 'mixed' in pandas_type:
  223. warnings.warn(
  224. "The DataFrame has column names of mixed type. They will be "
  225. "converted to strings and not roundtrip correctly.",
  226. UserWarning, stacklevel=4)
  227. if pandas_type == 'unicode':
  228. assert not extra_metadata
  229. extra_metadata = {'encoding': 'UTF-8'}
  230. return {
  231. 'name': name,
  232. 'field_name': name,
  233. 'pandas_type': pandas_type,
  234. 'numpy_type': string_dtype,
  235. 'metadata': extra_metadata,
  236. }
  237. def _column_name_to_strings(name):
  238. """Convert a column name (or level) to either a string or a recursive
  239. collection of strings.
  240. Parameters
  241. ----------
  242. name : str or tuple
  243. Returns
  244. -------
  245. value : str or tuple
  246. Examples
  247. --------
  248. >>> name = 'foo'
  249. >>> _column_name_to_strings(name)
  250. 'foo'
  251. >>> name = ('foo', 'bar')
  252. >>> _column_name_to_strings(name)
  253. ('foo', 'bar')
  254. >>> import pandas as pd
  255. >>> name = (1, pd.Timestamp('2017-02-01 00:00:00'))
  256. >>> _column_name_to_strings(name)
  257. ('1', '2017-02-01 00:00:00')
  258. """
  259. if isinstance(name, str):
  260. return name
  261. elif isinstance(name, bytes):
  262. # XXX: should we assume that bytes in Python 3 are UTF-8?
  263. return name.decode('utf8')
  264. elif isinstance(name, tuple):
  265. return str(tuple(map(_column_name_to_strings, name)))
  266. elif isinstance(name, Sequence):
  267. raise TypeError("Unsupported type for MultiIndex level")
  268. elif name is None:
  269. return None
  270. return str(name)
  271. def _index_level_name(index, i, column_names):
  272. """Return the name of an index level or a default name if `index.name` is
  273. None or is already a column name.
  274. Parameters
  275. ----------
  276. index : pandas.Index
  277. i : int
  278. Returns
  279. -------
  280. name : str
  281. """
  282. if index.name is not None and index.name not in column_names:
  283. return index.name
  284. else:
  285. return '__index_level_{:d}__'.format(i)
  286. def _get_columns_to_convert(df, schema, preserve_index, columns):
  287. columns = _resolve_columns_of_interest(df, schema, columns)
  288. if not df.columns.is_unique:
  289. raise ValueError(
  290. 'Duplicate column names found: {}'.format(list(df.columns))
  291. )
  292. if schema is not None:
  293. return _get_columns_to_convert_given_schema(df, schema, preserve_index)
  294. column_names = []
  295. index_levels = (
  296. _get_index_level_values(df.index) if preserve_index is not False
  297. else []
  298. )
  299. columns_to_convert = []
  300. convert_fields = []
  301. for name in columns:
  302. col = df[name]
  303. name = _column_name_to_strings(name)
  304. if _pandas_api.is_sparse(col):
  305. raise TypeError(
  306. "Sparse pandas data (column {}) not supported.".format(name))
  307. columns_to_convert.append(col)
  308. convert_fields.append(None)
  309. column_names.append(name)
  310. index_descriptors = []
  311. index_column_names = []
  312. for i, index_level in enumerate(index_levels):
  313. name = _index_level_name(index_level, i, column_names)
  314. if (isinstance(index_level, _pandas_api.pd.RangeIndex) and
  315. preserve_index is None):
  316. descr = _get_range_index_descriptor(index_level)
  317. else:
  318. columns_to_convert.append(index_level)
  319. convert_fields.append(None)
  320. descr = name
  321. index_column_names.append(name)
  322. index_descriptors.append(descr)
  323. all_names = column_names + index_column_names
  324. # all_names : all of the columns in the resulting table including the data
  325. # columns and serialized index columns
  326. # column_names : the names of the data columns
  327. # index_column_names : the names of the serialized index columns
  328. # index_descriptors : descriptions of each index to be used for
  329. # reconstruction
  330. # index_levels : the extracted index level values
  331. # columns_to_convert : assembled raw data (both data columns and indexes)
  332. # to be converted to Arrow format
  333. # columns_fields : specified column to use for coercion / casting
  334. # during serialization, if a Schema was provided
  335. return (all_names, column_names, index_column_names, index_descriptors,
  336. index_levels, columns_to_convert, convert_fields)
  337. def _get_columns_to_convert_given_schema(df, schema, preserve_index):
  338. """
  339. Specialized version of _get_columns_to_convert in case a Schema is
  340. specified.
  341. In that case, the Schema is used as the single point of truth for the
  342. table structure (types, which columns are included, order of columns, ...).
  343. """
  344. column_names = []
  345. columns_to_convert = []
  346. convert_fields = []
  347. index_descriptors = []
  348. index_column_names = []
  349. index_levels = []
  350. for name in schema.names:
  351. try:
  352. col = df[name]
  353. is_index = False
  354. except KeyError:
  355. try:
  356. col = _get_index_level(df, name)
  357. except (KeyError, IndexError):
  358. # name not found as index level
  359. raise KeyError(
  360. "name '{}' present in the specified schema is not found "
  361. "in the columns or index".format(name))
  362. if preserve_index is False:
  363. raise ValueError(
  364. "name '{}' present in the specified schema corresponds "
  365. "to the index, but 'preserve_index=False' was "
  366. "specified".format(name))
  367. elif (preserve_index is None and
  368. isinstance(col, _pandas_api.pd.RangeIndex)):
  369. raise ValueError(
  370. "name '{}' is present in the schema, but it is a "
  371. "RangeIndex which will not be converted as a column "
  372. "in the Table, but saved as metadata-only not in "
  373. "columns. Specify 'preserve_index=True' to force it "
  374. "being added as a column, or remove it from the "
  375. "specified schema".format(name))
  376. is_index = True
  377. name = _column_name_to_strings(name)
  378. if _pandas_api.is_sparse(col):
  379. raise TypeError(
  380. "Sparse pandas data (column {}) not supported.".format(name))
  381. field = schema.field(name)
  382. columns_to_convert.append(col)
  383. convert_fields.append(field)
  384. column_names.append(name)
  385. if is_index:
  386. index_column_names.append(name)
  387. index_descriptors.append(name)
  388. index_levels.append(col)
  389. all_names = column_names + index_column_names
  390. return (all_names, column_names, index_column_names, index_descriptors,
  391. index_levels, columns_to_convert, convert_fields)
  392. def _get_index_level(df, name):
  393. """
  394. Get the index level of a DataFrame given 'name' (column name in an arrow
  395. Schema).
  396. """
  397. key = name
  398. if name not in df.index.names and _is_generated_index_name(name):
  399. # we know we have an autogenerated name => extract number and get
  400. # the index level positionally
  401. key = int(name[len("__index_level_"):-2])
  402. return df.index.get_level_values(key)
  403. def _level_name(name):
  404. # preserve type when default serializable, otherwise str it
  405. try:
  406. json.dumps(name)
  407. return name
  408. except TypeError:
  409. return str(name)
  410. def _get_range_index_descriptor(level):
  411. # public start/stop/step attributes added in pandas 0.25.0
  412. return {
  413. 'kind': 'range',
  414. 'name': _level_name(level.name),
  415. 'start': _pandas_api.get_rangeindex_attribute(level, 'start'),
  416. 'stop': _pandas_api.get_rangeindex_attribute(level, 'stop'),
  417. 'step': _pandas_api.get_rangeindex_attribute(level, 'step')
  418. }
  419. def _get_index_level_values(index):
  420. n = len(getattr(index, 'levels', [index]))
  421. return [index.get_level_values(i) for i in range(n)]
  422. def _resolve_columns_of_interest(df, schema, columns):
  423. if schema is not None and columns is not None:
  424. raise ValueError('Schema and columns arguments are mutually '
  425. 'exclusive, pass only one of them')
  426. elif schema is not None:
  427. columns = schema.names
  428. elif columns is not None:
  429. columns = [c for c in columns if c in df.columns]
  430. else:
  431. columns = df.columns
  432. return columns
  433. def dataframe_to_types(df, preserve_index, columns=None):
  434. (all_names,
  435. column_names,
  436. _,
  437. index_descriptors,
  438. index_columns,
  439. columns_to_convert,
  440. _) = _get_columns_to_convert(df, None, preserve_index, columns)
  441. types = []
  442. # If pandas knows type, skip conversion
  443. for c in columns_to_convert:
  444. values = c.values
  445. if _pandas_api.is_categorical(values):
  446. type_ = pa.array(c, from_pandas=True).type
  447. elif _pandas_api.is_extension_array_dtype(values):
  448. type_ = pa.array(c.head(0), from_pandas=True).type
  449. else:
  450. values, type_ = get_datetimetz_type(values, c.dtype, None)
  451. type_ = pa.lib._ndarray_to_arrow_type(values, type_)
  452. if type_ is None:
  453. type_ = pa.array(c, from_pandas=True).type
  454. types.append(type_)
  455. metadata = construct_metadata(
  456. columns_to_convert, df, column_names, index_columns,
  457. index_descriptors, preserve_index, types
  458. )
  459. return all_names, types, metadata
  460. def dataframe_to_arrays(df, schema, preserve_index, nthreads=1, columns=None,
  461. safe=True):
  462. (all_names,
  463. column_names,
  464. index_column_names,
  465. index_descriptors,
  466. index_columns,
  467. columns_to_convert,
  468. convert_fields) = _get_columns_to_convert(df, schema, preserve_index,
  469. columns)
  470. # NOTE(wesm): If nthreads=None, then we use a heuristic to decide whether
  471. # using a thread pool is worth it. Currently the heuristic is whether the
  472. # nrows > 100 * ncols and ncols > 1.
  473. if nthreads is None:
  474. nrows, ncols = len(df), len(df.columns)
  475. if nrows > ncols * 100 and ncols > 1:
  476. nthreads = pa.cpu_count()
  477. else:
  478. nthreads = 1
  479. def convert_column(col, field):
  480. if field is None:
  481. field_nullable = True
  482. type_ = None
  483. else:
  484. field_nullable = field.nullable
  485. type_ = field.type
  486. try:
  487. result = pa.array(col, type=type_, from_pandas=True, safe=safe)
  488. except (pa.ArrowInvalid,
  489. pa.ArrowNotImplementedError,
  490. pa.ArrowTypeError) as e:
  491. e.args += ("Conversion failed for column {!s} with type {!s}"
  492. .format(col.name, col.dtype),)
  493. raise e
  494. if not field_nullable and result.null_count > 0:
  495. raise ValueError("Field {} was non-nullable but pandas column "
  496. "had {} null values".format(str(field),
  497. result.null_count))
  498. return result
  499. def _can_definitely_zero_copy(arr):
  500. return (isinstance(arr, np.ndarray) and
  501. arr.flags.contiguous and
  502. issubclass(arr.dtype.type, np.integer))
  503. if nthreads == 1:
  504. arrays = [convert_column(c, f)
  505. for c, f in zip(columns_to_convert, convert_fields)]
  506. else:
  507. arrays = []
  508. with futures.ThreadPoolExecutor(nthreads) as executor:
  509. for c, f in zip(columns_to_convert, convert_fields):
  510. if _can_definitely_zero_copy(c.values):
  511. arrays.append(convert_column(c, f))
  512. else:
  513. arrays.append(executor.submit(convert_column, c, f))
  514. for i, maybe_fut in enumerate(arrays):
  515. if isinstance(maybe_fut, futures.Future):
  516. arrays[i] = maybe_fut.result()
  517. types = [x.type for x in arrays]
  518. if schema is None:
  519. fields = []
  520. for name, type_ in zip(all_names, types):
  521. name = name if name is not None else 'None'
  522. fields.append(pa.field(name, type_))
  523. schema = pa.schema(fields)
  524. pandas_metadata = construct_metadata(
  525. columns_to_convert, df, column_names, index_columns,
  526. index_descriptors, preserve_index, types
  527. )
  528. metadata = deepcopy(schema.metadata) if schema.metadata else dict()
  529. metadata.update(pandas_metadata)
  530. schema = schema.with_metadata(metadata)
  531. return arrays, schema
  532. def get_datetimetz_type(values, dtype, type_):
  533. if values.dtype.type != np.datetime64:
  534. return values, type_
  535. if _pandas_api.is_datetimetz(dtype) and type_ is None:
  536. # If no user type passed, construct a tz-aware timestamp type
  537. tz = dtype.tz
  538. unit = dtype.unit
  539. type_ = pa.timestamp(unit, tz)
  540. elif type_ is None:
  541. # Trust the NumPy dtype
  542. type_ = pa.from_numpy_dtype(values.dtype)
  543. return values, type_
  544. # ----------------------------------------------------------------------
  545. # Converting pandas.DataFrame to a dict containing only NumPy arrays or other
  546. # objects friendly to pyarrow.serialize
  547. def dataframe_to_serialized_dict(frame):
  548. block_manager = frame._data
  549. blocks = []
  550. axes = [ax for ax in block_manager.axes]
  551. for block in block_manager.blocks:
  552. values = block.values
  553. block_data = {}
  554. if _pandas_api.is_datetimetz(values.dtype):
  555. block_data['timezone'] = pa.lib.tzinfo_to_string(values.tz)
  556. if hasattr(values, 'values'):
  557. values = values.values
  558. elif _pandas_api.is_categorical(values):
  559. block_data.update(dictionary=values.categories,
  560. ordered=values.ordered)
  561. values = values.codes
  562. block_data.update(
  563. placement=block.mgr_locs.as_array,
  564. block=values
  565. )
  566. # If we are dealing with an object array, pickle it instead.
  567. if values.dtype == np.dtype(object):
  568. block_data['object'] = None
  569. block_data['block'] = builtin_pickle.dumps(
  570. values, protocol=builtin_pickle.HIGHEST_PROTOCOL)
  571. blocks.append(block_data)
  572. return {
  573. 'blocks': blocks,
  574. 'axes': axes
  575. }
  576. def serialized_dict_to_dataframe(data):
  577. import pandas.core.internals as _int
  578. reconstructed_blocks = [_reconstruct_block(block)
  579. for block in data['blocks']]
  580. block_mgr = _int.BlockManager(reconstructed_blocks, data['axes'])
  581. return _pandas_api.data_frame(block_mgr)
  582. def _reconstruct_block(item, columns=None, extension_columns=None):
  583. """
  584. Construct a pandas Block from the `item` dictionary coming from pyarrow's
  585. serialization or returned by arrow::python::ConvertTableToPandas.
  586. This function takes care of converting dictionary types to pandas
  587. categorical, Timestamp-with-timezones to the proper pandas Block, and
  588. conversion to pandas ExtensionBlock
  589. Parameters
  590. ----------
  591. item : dict
  592. For basic types, this is a dictionary in the form of
  593. {'block': np.ndarray of values, 'placement': pandas block placement}.
  594. Additional keys are present for other types (dictionary, timezone,
  595. object).
  596. columns :
  597. Column names of the table being constructed, used for extension types
  598. extension_columns : dict
  599. Dictionary of {column_name: pandas_dtype} that includes all columns
  600. and corresponding dtypes that will be converted to a pandas
  601. ExtensionBlock.
  602. Returns
  603. -------
  604. pandas Block
  605. """
  606. import pandas.core.internals as _int
  607. block_arr = item.get('block', None)
  608. placement = item['placement']
  609. if 'dictionary' in item:
  610. cat = _pandas_api.categorical_type.from_codes(
  611. block_arr, categories=item['dictionary'],
  612. ordered=item['ordered'])
  613. block = _int.make_block(cat, placement=placement)
  614. elif 'timezone' in item:
  615. dtype = make_datetimetz(item['timezone'])
  616. block = _int.make_block(block_arr, placement=placement,
  617. klass=_int.DatetimeTZBlock,
  618. dtype=dtype)
  619. elif 'object' in item:
  620. block = _int.make_block(builtin_pickle.loads(block_arr),
  621. placement=placement)
  622. elif 'py_array' in item:
  623. # create ExtensionBlock
  624. arr = item['py_array']
  625. assert len(placement) == 1
  626. name = columns[placement[0]]
  627. pandas_dtype = extension_columns[name]
  628. if not hasattr(pandas_dtype, '__from_arrow__'):
  629. raise ValueError("This column does not support to be converted "
  630. "to a pandas ExtensionArray")
  631. pd_ext_arr = pandas_dtype.__from_arrow__(arr)
  632. block = _int.make_block(pd_ext_arr, placement=placement)
  633. else:
  634. block = _int.make_block(block_arr, placement=placement)
  635. return block
  636. def make_datetimetz(tz):
  637. tz = pa.lib.string_to_tzinfo(tz)
  638. return _pandas_api.datetimetz_type('ns', tz=tz)
  639. # ----------------------------------------------------------------------
  640. # Converting pyarrow.Table efficiently to pandas.DataFrame
  641. def table_to_blockmanager(options, table, categories=None,
  642. ignore_metadata=False, types_mapper=None):
  643. from pandas.core.internals import BlockManager
  644. all_columns = []
  645. column_indexes = []
  646. pandas_metadata = table.schema.pandas_metadata
  647. if not ignore_metadata and pandas_metadata is not None:
  648. all_columns = pandas_metadata['columns']
  649. column_indexes = pandas_metadata.get('column_indexes', [])
  650. index_descriptors = pandas_metadata['index_columns']
  651. table = _add_any_metadata(table, pandas_metadata)
  652. table, index = _reconstruct_index(table, index_descriptors,
  653. all_columns)
  654. ext_columns_dtypes = _get_extension_dtypes(
  655. table, all_columns, types_mapper)
  656. else:
  657. index = _pandas_api.pd.RangeIndex(table.num_rows)
  658. ext_columns_dtypes = _get_extension_dtypes(table, [], types_mapper)
  659. _check_data_column_metadata_consistency(all_columns)
  660. columns = _deserialize_column_index(table, all_columns, column_indexes)
  661. blocks = _table_to_blocks(options, table, categories, ext_columns_dtypes)
  662. axes = [columns, index]
  663. return BlockManager(blocks, axes)
  664. # Set of the string repr of all numpy dtypes that can be stored in a pandas
  665. # dataframe (complex not included since not supported by Arrow)
  666. _pandas_supported_numpy_types = {
  667. str(np.dtype(typ))
  668. for typ in (np.sctypes['int'] + np.sctypes['uint'] + np.sctypes['float'] +
  669. ['object', 'bool'])
  670. }
  671. def _get_extension_dtypes(table, columns_metadata, types_mapper=None):
  672. """
  673. Based on the stored column pandas metadata and the extension types
  674. in the arrow schema, infer which columns should be converted to a
  675. pandas extension dtype.
  676. The 'numpy_type' field in the column metadata stores the string
  677. representation of the original pandas dtype (and, despite its name,
  678. not the 'pandas_type' field).
  679. Based on this string representation, a pandas/numpy dtype is constructed
  680. and then we can check if this dtype supports conversion from arrow.
  681. """
  682. ext_columns = {}
  683. # older pandas version that does not yet support extension dtypes
  684. if _pandas_api.extension_dtype is None:
  685. return ext_columns
  686. # infer the extension columns from the pandas metadata
  687. for col_meta in columns_metadata:
  688. name = col_meta['name']
  689. dtype = col_meta['numpy_type']
  690. if dtype not in _pandas_supported_numpy_types:
  691. # pandas_dtype is expensive, so avoid doing this for types
  692. # that are certainly numpy dtypes
  693. pandas_dtype = _pandas_api.pandas_dtype(dtype)
  694. if isinstance(pandas_dtype, _pandas_api.extension_dtype):
  695. if hasattr(pandas_dtype, "__from_arrow__"):
  696. ext_columns[name] = pandas_dtype
  697. # infer from extension type in the schema
  698. for field in table.schema:
  699. typ = field.type
  700. if isinstance(typ, pa.BaseExtensionType):
  701. try:
  702. pandas_dtype = typ.to_pandas_dtype()
  703. except NotImplementedError:
  704. pass
  705. else:
  706. ext_columns[field.name] = pandas_dtype
  707. # use the specified mapping of built-in arrow types to pandas dtypes
  708. if types_mapper:
  709. for field in table.schema:
  710. typ = field.type
  711. pandas_dtype = types_mapper(typ)
  712. if pandas_dtype is not None:
  713. ext_columns[field.name] = pandas_dtype
  714. return ext_columns
  715. def _check_data_column_metadata_consistency(all_columns):
  716. # It can never be the case in a released version of pyarrow that
  717. # c['name'] is None *and* 'field_name' is not a key in the column metadata,
  718. # because the change to allow c['name'] to be None and the change to add
  719. # 'field_name' are in the same release (0.8.0)
  720. assert all(
  721. (c['name'] is None and 'field_name' in c) or c['name'] is not None
  722. for c in all_columns
  723. )
  724. def _deserialize_column_index(block_table, all_columns, column_indexes):
  725. column_strings = [frombytes(x) if isinstance(x, bytes) else x
  726. for x in block_table.column_names]
  727. if all_columns:
  728. columns_name_dict = {
  729. c.get('field_name', _column_name_to_strings(c['name'])): c['name']
  730. for c in all_columns
  731. }
  732. columns_values = [
  733. columns_name_dict.get(name, name) for name in column_strings
  734. ]
  735. else:
  736. columns_values = column_strings
  737. # If we're passed multiple column indexes then evaluate with
  738. # ast.literal_eval, since the column index values show up as a list of
  739. # tuples
  740. to_pair = ast.literal_eval if len(column_indexes) > 1 else lambda x: (x,)
  741. # Create the column index
  742. # Construct the base index
  743. if not columns_values:
  744. columns = _pandas_api.pd.Index(columns_values)
  745. else:
  746. columns = _pandas_api.pd.MultiIndex.from_tuples(
  747. list(map(to_pair, columns_values)),
  748. names=[col_index['name'] for col_index in column_indexes] or None,
  749. )
  750. # if we're reconstructing the index
  751. if len(column_indexes) > 0:
  752. columns = _reconstruct_columns_from_metadata(columns, column_indexes)
  753. # ARROW-1751: flatten a single level column MultiIndex for pandas 0.21.0
  754. columns = _flatten_single_level_multiindex(columns)
  755. return columns
  756. def _reconstruct_index(table, index_descriptors, all_columns):
  757. # 0. 'field_name' is the name of the column in the arrow Table
  758. # 1. 'name' is the user-facing name of the column, that is, it came from
  759. # pandas
  760. # 2. 'field_name' and 'name' differ for index columns
  761. # 3. We fall back on c['name'] for backwards compatibility
  762. field_name_to_metadata = {
  763. c.get('field_name', c['name']): c
  764. for c in all_columns
  765. }
  766. # Build up a list of index columns and names while removing those columns
  767. # from the original table
  768. index_arrays = []
  769. index_names = []
  770. result_table = table
  771. for descr in index_descriptors:
  772. if isinstance(descr, str):
  773. result_table, index_level, index_name = _extract_index_level(
  774. table, result_table, descr, field_name_to_metadata)
  775. if index_level is None:
  776. # ARROW-1883: the serialized index column was not found
  777. continue
  778. elif descr['kind'] == 'range':
  779. index_name = descr['name']
  780. index_level = _pandas_api.pd.RangeIndex(descr['start'],
  781. descr['stop'],
  782. step=descr['step'],
  783. name=index_name)
  784. if len(index_level) != len(table):
  785. # Possibly the result of munged metadata
  786. continue
  787. else:
  788. raise ValueError("Unrecognized index kind: {}"
  789. .format(descr['kind']))
  790. index_arrays.append(index_level)
  791. index_names.append(index_name)
  792. pd = _pandas_api.pd
  793. # Reconstruct the row index
  794. if len(index_arrays) > 1:
  795. index = pd.MultiIndex.from_arrays(index_arrays, names=index_names)
  796. elif len(index_arrays) == 1:
  797. index = index_arrays[0]
  798. if not isinstance(index, pd.Index):
  799. # Box anything that wasn't boxed above
  800. index = pd.Index(index, name=index_names[0])
  801. else:
  802. index = pd.RangeIndex(table.num_rows)
  803. return result_table, index
  804. def _extract_index_level(table, result_table, field_name,
  805. field_name_to_metadata):
  806. logical_name = field_name_to_metadata[field_name]['name']
  807. index_name = _backwards_compatible_index_name(field_name, logical_name)
  808. i = table.schema.get_field_index(field_name)
  809. if i == -1:
  810. # The serialized index column was removed by the user
  811. return result_table, None, None
  812. pd = _pandas_api.pd
  813. col = table.column(i)
  814. values = col.to_pandas().values
  815. if hasattr(values, 'flags') and not values.flags.writeable:
  816. # ARROW-1054: in pandas 0.19.2, factorize will reject
  817. # non-writeable arrays when calling MultiIndex.from_arrays
  818. values = values.copy()
  819. if isinstance(col.type, pa.lib.TimestampType) and col.type.tz is not None:
  820. index_level = make_tz_aware(pd.Series(values), col.type.tz)
  821. else:
  822. index_level = pd.Series(values, dtype=values.dtype)
  823. result_table = result_table.remove_column(
  824. result_table.schema.get_field_index(field_name)
  825. )
  826. return result_table, index_level, index_name
  827. def _backwards_compatible_index_name(raw_name, logical_name):
  828. """Compute the name of an index column that is compatible with older
  829. versions of :mod:`pyarrow`.
  830. Parameters
  831. ----------
  832. raw_name : str
  833. logical_name : str
  834. Returns
  835. -------
  836. result : str
  837. Notes
  838. -----
  839. * Part of :func:`~pyarrow.pandas_compat.table_to_blockmanager`
  840. """
  841. # Part of table_to_blockmanager
  842. if raw_name == logical_name and _is_generated_index_name(raw_name):
  843. return None
  844. else:
  845. return logical_name
  846. def _is_generated_index_name(name):
  847. pattern = r'^__index_level_\d+__$'
  848. return re.match(pattern, name) is not None
  849. _pandas_logical_type_map = {
  850. 'date': 'datetime64[D]',
  851. 'datetime': 'datetime64[ns]',
  852. 'unicode': np.unicode_,
  853. 'bytes': np.bytes_,
  854. 'string': np.str_,
  855. 'integer': np.int64,
  856. 'floating': np.float64,
  857. 'empty': np.object_,
  858. }
  859. def _pandas_type_to_numpy_type(pandas_type):
  860. """Get the numpy dtype that corresponds to a pandas type.
  861. Parameters
  862. ----------
  863. pandas_type : str
  864. The result of a call to pandas.lib.infer_dtype.
  865. Returns
  866. -------
  867. dtype : np.dtype
  868. The dtype that corresponds to `pandas_type`.
  869. """
  870. try:
  871. return _pandas_logical_type_map[pandas_type]
  872. except KeyError:
  873. if 'mixed' in pandas_type:
  874. # catching 'mixed', 'mixed-integer' and 'mixed-integer-float'
  875. return np.object_
  876. return np.dtype(pandas_type)
  877. def _get_multiindex_codes(mi):
  878. # compat for pandas < 0.24 (MI labels renamed to codes).
  879. if isinstance(mi, _pandas_api.pd.MultiIndex):
  880. return mi.codes if hasattr(mi, 'codes') else mi.labels
  881. else:
  882. return None
  883. def _reconstruct_columns_from_metadata(columns, column_indexes):
  884. """Construct a pandas MultiIndex from `columns` and column index metadata
  885. in `column_indexes`.
  886. Parameters
  887. ----------
  888. columns : List[pd.Index]
  889. The columns coming from a pyarrow.Table
  890. column_indexes : List[Dict[str, str]]
  891. The column index metadata deserialized from the JSON schema metadata
  892. in a :class:`~pyarrow.Table`.
  893. Returns
  894. -------
  895. result : MultiIndex
  896. The index reconstructed using `column_indexes` metadata with levels of
  897. the correct type.
  898. Notes
  899. -----
  900. * Part of :func:`~pyarrow.pandas_compat.table_to_blockmanager`
  901. """
  902. pd = _pandas_api.pd
  903. # Get levels and labels, and provide sane defaults if the index has a
  904. # single level to avoid if/else spaghetti.
  905. levels = getattr(columns, 'levels', None) or [columns]
  906. labels = _get_multiindex_codes(columns) or [
  907. pd.RangeIndex(len(level)) for level in levels
  908. ]
  909. # Convert each level to the dtype provided in the metadata
  910. levels_dtypes = [
  911. (level, col_index.get('pandas_type', str(level.dtype)),
  912. col_index.get('numpy_type', None))
  913. for level, col_index in zip_longest(
  914. levels, column_indexes, fillvalue={}
  915. )
  916. ]
  917. new_levels = []
  918. encoder = operator.methodcaller('encode', 'UTF-8')
  919. for level, pandas_dtype, numpy_dtype in levels_dtypes:
  920. dtype = _pandas_type_to_numpy_type(pandas_dtype)
  921. # Since our metadata is UTF-8 encoded, Python turns things that were
  922. # bytes into unicode strings when json.loads-ing them. We need to
  923. # convert them back to bytes to preserve metadata.
  924. if dtype == np.bytes_:
  925. level = level.map(encoder)
  926. elif level.dtype != dtype:
  927. level = level.astype(dtype)
  928. # ARROW-9096: if original DataFrame was upcast we keep that
  929. if level.dtype != numpy_dtype:
  930. level = level.astype(numpy_dtype)
  931. new_levels.append(level)
  932. return pd.MultiIndex(new_levels, labels, names=columns.names)
  933. def _table_to_blocks(options, block_table, categories, extension_columns):
  934. # Part of table_to_blockmanager
  935. # Convert an arrow table to Block from the internal pandas API
  936. columns = block_table.column_names
  937. result = pa.lib.table_to_blocks(options, block_table, categories,
  938. list(extension_columns.keys()))
  939. return [_reconstruct_block(item, columns, extension_columns)
  940. for item in result]
  941. def _flatten_single_level_multiindex(index):
  942. pd = _pandas_api.pd
  943. if isinstance(index, pd.MultiIndex) and index.nlevels == 1:
  944. levels, = index.levels
  945. labels, = _get_multiindex_codes(index)
  946. # ARROW-9096: use levels.dtype to match cast with original DataFrame
  947. dtype = levels.dtype
  948. # Cheaply check that we do not somehow have duplicate column names
  949. if not index.is_unique:
  950. raise ValueError('Found non-unique column index')
  951. return pd.Index(
  952. [levels[_label] if _label != -1 else None for _label in labels],
  953. dtype=dtype,
  954. name=index.names[0]
  955. )
  956. return index
  957. def _add_any_metadata(table, pandas_metadata):
  958. modified_columns = {}
  959. modified_fields = {}
  960. schema = table.schema
  961. index_columns = pandas_metadata['index_columns']
  962. # only take index columns into account if they are an actual table column
  963. index_columns = [idx_col for idx_col in index_columns
  964. if isinstance(idx_col, str)]
  965. n_index_levels = len(index_columns)
  966. n_columns = len(pandas_metadata['columns']) - n_index_levels
  967. # Add time zones
  968. for i, col_meta in enumerate(pandas_metadata['columns']):
  969. raw_name = col_meta.get('field_name')
  970. if not raw_name:
  971. # deal with metadata written with arrow < 0.8 or fastparquet
  972. raw_name = col_meta['name']
  973. if i >= n_columns:
  974. # index columns
  975. raw_name = index_columns[i - n_columns]
  976. if raw_name is None:
  977. raw_name = 'None'
  978. idx = schema.get_field_index(raw_name)
  979. if idx != -1:
  980. if col_meta['pandas_type'] == 'datetimetz':
  981. col = table[idx]
  982. if not isinstance(col.type, pa.lib.TimestampType):
  983. continue
  984. metadata = col_meta['metadata']
  985. if not metadata:
  986. continue
  987. metadata_tz = metadata.get('timezone')
  988. if metadata_tz and metadata_tz != col.type.tz:
  989. converted = col.to_pandas()
  990. tz_aware_type = pa.timestamp('ns', tz=metadata_tz)
  991. with_metadata = pa.Array.from_pandas(converted,
  992. type=tz_aware_type)
  993. modified_fields[idx] = pa.field(schema[idx].name,
  994. tz_aware_type)
  995. modified_columns[idx] = with_metadata
  996. if len(modified_columns) > 0:
  997. columns = []
  998. fields = []
  999. for i in range(len(table.schema)):
  1000. if i in modified_columns:
  1001. columns.append(modified_columns[i])
  1002. fields.append(modified_fields[i])
  1003. else:
  1004. columns.append(table[i])
  1005. fields.append(table.schema[i])
  1006. return pa.Table.from_arrays(columns, schema=pa.schema(fields))
  1007. else:
  1008. return table
  1009. # ----------------------------------------------------------------------
  1010. # Helper functions used in lib
  1011. def make_tz_aware(series, tz):
  1012. """
  1013. Make a datetime64 Series timezone-aware for the given tz
  1014. """
  1015. tz = pa.lib.string_to_tzinfo(tz)
  1016. series = (series.dt.tz_localize('utc')
  1017. .dt.tz_convert(tz))
  1018. return series