Skip to content

Commit e36b30b

Browse files
author
tworec
committed
BUG: fix read_gbq lost numeric precision
fixes: - lost precision for longs above 2^53 - and floats above 10k
1 parent 7dedbed commit e36b30b

File tree

3 files changed

+190
-56
lines changed

3 files changed

+190
-56
lines changed

doc/source/io.rst

+47-17
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ object.
3838
* :ref:`read_json<io.json_reader>`
3939
* :ref:`read_msgpack<io.msgpack>` (experimental)
4040
* :ref:`read_html<io.read_html>`
41-
* :ref:`read_gbq<io.bigquery_reader>` (experimental)
41+
* :ref:`read_gbq<io.bigquery>` (experimental)
4242
* :ref:`read_stata<io.stata_reader>`
4343
* :ref:`read_sas<io.sas_reader>`
4444
* :ref:`read_clipboard<io.clipboard>`
@@ -53,7 +53,7 @@ The corresponding ``writer`` functions are object methods that are accessed like
5353
* :ref:`to_json<io.json_writer>`
5454
* :ref:`to_msgpack<io.msgpack>` (experimental)
5555
* :ref:`to_html<io.html>`
56-
* :ref:`to_gbq<io.bigquery_writer>` (experimental)
56+
* :ref:`to_gbq<io.bigquery>` (experimental)
5757
* :ref:`to_stata<io.stata_writer>`
5858
* :ref:`to_clipboard<io.clipboard>`
5959
* :ref:`to_pickle<io.pickle>`
@@ -4428,16 +4428,11 @@ DataFrame with a shape and data types derived from the source table.
44284428
Additionally, DataFrames can be inserted into new BigQuery tables or appended
44294429
to existing tables.
44304430

4431-
You will need to install some additional dependencies:
4432-
4433-
- Google's `python-gflags <https://github.com/google/python-gflags/>`__
4434-
- `httplib2 <http://pypi.python.org/pypi/httplib2>`__
4435-
- `google-api-python-client <http://github.com/google/google-api-python-client>`__
4436-
44374431
.. warning::
44384432

44394433
To use this module, you will need a valid BigQuery account. Refer to the
4440-
`BigQuery Documentation <https://cloud.google.com/bigquery/what-is-bigquery>`__ for details on the service itself.
4434+
`BigQuery Documentation <https://cloud.google.com/bigquery/what-is-bigquery>`__
4435+
for details on the service itself.
44414436

44424437
The key functions are:
44434438

@@ -4451,22 +4446,58 @@ The key functions are:
44514446

44524447
.. currentmodule:: pandas
44534448

4454-
.. _io.bigquery_reader:
4449+
4450+
Supported Data Types
4451+
++++++++++++++++++++
4452+
4453+
Pandas supports these all `BigQuery data types <https://cloud.google.com/bigquery/data-types>`__:
4454+
``STRING``, ``INTEGER`` (64bit), ``FLOAT`` (64 bit), ``BOOLEAN`` and
4455+
``TIMESTAMP`` (microsecond precision). Data types ``BYTES`` and ``RECORD``
4456+
are not supported.
4457+
4458+
Integer and boolean ``NA`` handling
4459+
+++++++++++++++++++++++++++++++
4460+
4461+
.. versionadded:: 0.19
4462+
4463+
Since all columns in BigQuery queries are nullable, and NumPy lacks of ``NA``
4464+
support for integer and boolean types, this module will store ``INTEGER`` or
4465+
``BOOLEAN`` columns with at least one ``NULL`` value as ``dtype=object``.
4466+
Otherwise those columns will be stored as ``dtype=int64`` or ``dtype=bool``
4467+
respectively.
4468+
4469+
This is opposite to default pandas behaviour which will promote integer
4470+
type to float in order to store NAs. See the :ref:`gotchas<gotchas.intna>`
4471+
for detailed explaination.
4472+
4473+
While this trade-off works well for most cases, it breaks down for storing
4474+
values greater than 2**53. Such values in BigQuery can represent identifiers
4475+
and unnoticed precision lost for identifier is what we want to avoid.
4476+
4477+
Dependencies
4478+
++++++++++++
4479+
4480+
This module requires these additional dependencies:
4481+
4482+
- `httplib2 <http://pypi.python.org/pypi/httplib2>`__
4483+
- `google-api-python-client <http://github.com/google/google-api-python-client>`__
4484+
- `oauth2client <https://github.com/google/oauth2client>`__.
4485+
44554486

44564487
.. _io.bigquery_authentication:
44574488

44584489
Authentication
44594490
''''''''''''''
44604491

4461-
.. versionadded:: 0.18.0
4492+
.. versionadded:: 0.18
44624493

44634494
Authentication to the Google ``BigQuery`` service is via ``OAuth 2.0``.
44644495
Is possible to authenticate with either user account credentials or service account credentials.
44654496

44664497
Authenticating with user account credentials is as simple as following the prompts in a browser window
44674498
which will be automatically opened for you. You will be authenticated to the specified
44684499
``BigQuery`` account using the product name ``pandas GBQ``. It is only possible on local host.
4469-
The remote authentication using user account credentials is not currently supported in Pandas.
4500+
The remote authentication using user account credentials is not currently supported in pandas.
44704501
Additional information on the authentication mechanism can be found
44714502
`here <https://developers.google.com/identity/protocols/OAuth2#clientside/>`__.
44724503

@@ -4475,17 +4506,13 @@ is particularly useful when working on remote servers (eg. jupyter iPython noteb
44754506
Additional information on service accounts can be found
44764507
`here <https://developers.google.com/identity/protocols/OAuth2#serviceaccount>`__.
44774508

4478-
You will need to install an additional dependency: `oauth2client <https://github.com/google/oauth2client>`__.
4479-
44804509
Authentication via ``application default credentials`` is also possible. This is only valid
44814510
if the parameter ``private_key`` is not provided. This method also requires that
44824511
the credentials can be fetched from the environment the code is running in.
44834512
Otherwise, the OAuth2 client-side authentication is used.
44844513
Additional information on
44854514
`application default credentials <https://developers.google.com/identity/protocols/application-default-credentials>`__.
44864515

4487-
.. versionadded:: 0.19.0
4488-
44894516
.. note::
44904517

44914518
The `'private_key'` parameter can be set to either the file path of the service account key
@@ -4496,6 +4523,7 @@ Additional information on
44964523
A private key can be obtained from the Google developers console by clicking
44974524
`here <https://console.developers.google.com/permissions/serviceaccounts>`__. Use JSON key type.
44984525

4526+
.. _io.bigquery_reader:
44994527

45004528
Querying
45014529
''''''''
@@ -4539,7 +4567,6 @@ destination DataFrame as well as a preferred column order as follows:
45394567

45404568
.. _io.bigquery_writer:
45414569

4542-
45434570
Writing DataFrames
45444571
''''''''''''''''''
45454572

@@ -4629,6 +4656,8 @@ For example:
46294656
often as the service seems to be changing and evolving. BiqQuery is best for analyzing large
46304657
sets of data quickly, but it is not a direct replacement for a transactional database.
46314658

4659+
.. _io.bigquery_create_tables:
4660+
46324661
Creating BigQuery Tables
46334662
''''''''''''''''''''''''
46344663

@@ -4658,6 +4687,7 @@ produce the dictionary representation schema of the specified pandas DataFrame.
46584687
the new table with a different name. Refer to
46594688
`Google BigQuery issue 191 <https://code.google.com/p/google-bigquery/issues/detail?id=191>`__.
46604689

4690+
46614691
.. _io.stata:
46624692

46634693
Stata Format

pandas/io/gbq.py

+13-11
Original file line numberDiff line numberDiff line change
@@ -586,18 +586,14 @@ def _parse_data(schema, rows):
586586
# see:
587587
# http://pandas.pydata.org/pandas-docs/dev/missing_data.html
588588
# #missing-data-casting-rules-and-indexing
589-
dtype_map = {'INTEGER': np.dtype(float),
590-
'FLOAT': np.dtype(float),
591-
# This seems to be buggy without nanosecond indicator
589+
dtype_map = {'FLOAT': np.dtype(float),
592590
'TIMESTAMP': 'M8[ns]'}
593591

594592
fields = schema['fields']
595593
col_types = [field['type'] for field in fields]
596594
col_names = [str(field['name']) for field in fields]
597595
col_dtypes = [dtype_map.get(field['type'], object) for field in fields]
598-
page_array = np.zeros((len(rows),),
599-
dtype=lzip(col_names, col_dtypes))
600-
596+
page_array = np.zeros((len(rows),), dtype=lzip(col_names, col_dtypes))
601597
for row_num, raw_row in enumerate(rows):
602598
entries = raw_row.get('f', [])
603599
for col_num, field_type in enumerate(col_types):
@@ -611,7 +607,9 @@ def _parse_data(schema, rows):
611607
def _parse_entry(field_value, field_type):
612608
if field_value is None or field_value == 'null':
613609
return None
614-
if field_type == 'INTEGER' or field_type == 'FLOAT':
610+
if field_type == 'INTEGER':
611+
return int(field_value)
612+
elif field_type == 'FLOAT':
615613
return float(field_value)
616614
elif field_type == 'TIMESTAMP':
617615
timestamp = datetime.utcfromtimestamp(float(field_value))
@@ -728,10 +726,14 @@ def read_gbq(query, project_id=None, index_col=None, col_order=None,
728726
'Column order does not match this DataFrame.'
729727
)
730728

731-
# Downcast floats to integers and objects to booleans
732-
# if there are no NaN's. This is presently due to a
733-
# limitation of numpy in handling missing data.
734-
final_df._data = final_df._data.downcast(dtypes='infer')
729+
# cast BOOLEAN and INTEGER columns from object to bool/int
730+
# if they dont have any nulls
731+
type_map = {'BOOLEAN': bool, 'INTEGER': int}
732+
for field in schema['fields']:
733+
if field['type'] in type_map and \
734+
final_df[field['name']].notnull().all():
735+
final_df[field['name']] = \
736+
final_df[field['name']].astype(type_map[field['type']])
735737

736738
connector.print_elapsed_seconds(
737739
'Total time taken',

0 commit comments

Comments
 (0)