Skip to content

Commit 2407e4e

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 794f792 commit 2407e4e

File tree

5 files changed

+197
-61
lines changed

5 files changed

+197
-61
lines changed

doc/source/install.rst

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -249,9 +249,9 @@ Optional Dependencies
249249
* `PyTables <http://www.pytables.org>`__: necessary for HDF5-based storage. Version 3.0.0 or higher required, Version 3.2.1 or higher highly recommended.
250250
* `SQLAlchemy <http://www.sqlalchemy.org>`__: for SQL database support. Version 0.8.1 or higher recommended. Besides SQLAlchemy, you also need a database specific driver. You can find an overview of supported drivers for each SQL dialect in the `SQLAlchemy docs <http://docs.sqlalchemy.org/en/latest/dialects/index.html>`__. Some common drivers are:
251251

252-
- `psycopg2 <http://initd.org/psycopg/>`__: for PostgreSQL
253-
- `pymysql <https://github.com/PyMySQL/PyMySQL>`__: for MySQL.
254-
- `SQLite <https://docs.python.org/3.5/library/sqlite3.html>`__: for SQLite, this is included in Python's standard library by default.
252+
* `psycopg2 <http://initd.org/psycopg/>`__: for PostgreSQL
253+
* `pymysql <https://github.com/PyMySQL/PyMySQL>`__: for MySQL.
254+
* `SQLite <https://docs.python.org/3.5/library/sqlite3.html>`__: for SQLite, this is included in Python's standard library by default.
255255

256256
* `matplotlib <http://matplotlib.org/>`__: for plotting
257257
* For Excel I/O:
@@ -271,11 +271,8 @@ Optional Dependencies
271271
<http://www.vergenet.net/~conrad/software/xsel/>`__, or `xclip
272272
<https://github.com/astrand/xclip/>`__: necessary to use
273273
:func:`~pandas.read_clipboard`. Most package managers on Linux distributions will have ``xclip`` and/or ``xsel`` immediately available for installation.
274-
* Google's `python-gflags <<https://github.com/google/python-gflags/>`__ ,
275-
`oauth2client <https://github.com/google/oauth2client>`__ ,
276-
`httplib2 <http://pypi.python.org/pypi/httplib2>`__
277-
and `google-api-python-client <http://github.com/google/google-api-python-client>`__
278-
: Needed for :mod:`~pandas.io.gbq`
274+
* For Google BigQuery I/O - see :ref:`here <io.bigquery_deps>`.
275+
279276
* `Backports.lzma <https://pypi.python.org/pypi/backports.lzma/>`__: Only for Python 2, for writing to and/or reading from an xz compressed DataFrame in CSV; Python 3 support is built into the standard library.
280277
* One of the following combinations of libraries is needed to use the
281278
top-level :func:`~pandas.read_html` function:

doc/source/io.rst

Lines changed: 47 additions & 14 deletions
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>`
@@ -4429,16 +4429,11 @@ DataFrame with a shape and data types derived from the source table.
44294429
Additionally, DataFrames can be inserted into new BigQuery tables or appended
44304430
to existing tables.
44314431

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

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

44434438
The key functions are:
44444439

@@ -4452,7 +4447,44 @@ The key functions are:
44524447

44534448
.. currentmodule:: pandas
44544449

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

44574489
.. _io.bigquery_authentication:
44584490

@@ -4467,7 +4499,7 @@ Is possible to authenticate with either user account credentials or service acco
44674499
Authenticating with user account credentials is as simple as following the prompts in a browser window
44684500
which will be automatically opened for you. You will be authenticated to the specified
44694501
``BigQuery`` account using the product name ``pandas GBQ``. It is only possible on local host.
4470-
The remote authentication using user account credentials is not currently supported in Pandas.
4502+
The remote authentication using user account credentials is not currently supported in pandas.
44714503
Additional information on the authentication mechanism can be found
44724504
`here <https://developers.google.com/identity/protocols/OAuth2#clientside/>`__.
44734505

@@ -4476,8 +4508,6 @@ is particularly useful when working on remote servers (eg. jupyter iPython noteb
44764508
Additional information on service accounts can be found
44774509
`here <https://developers.google.com/identity/protocols/OAuth2#serviceaccount>`__.
44784510

4479-
You will need to install an additional dependency: `oauth2client <https://github.com/google/oauth2client>`__.
4480-
44814511
Authentication via ``application default credentials`` is also possible. This is only valid
44824512
if the parameter ``private_key`` is not provided. This method also requires that
44834513
the credentials can be fetched from the environment the code is running in.
@@ -4497,6 +4527,7 @@ Additional information on
44974527
A private key can be obtained from the Google developers console by clicking
44984528
`here <https://console.developers.google.com/permissions/serviceaccounts>`__. Use JSON key type.
44994529

4530+
.. _io.bigquery_reader:
45004531

45014532
Querying
45024533
''''''''
@@ -4540,7 +4571,6 @@ destination DataFrame as well as a preferred column order as follows:
45404571

45414572
.. _io.bigquery_writer:
45424573

4543-
45444574
Writing DataFrames
45454575
''''''''''''''''''
45464576

@@ -4630,6 +4660,8 @@ For example:
46304660
often as the service seems to be changing and evolving. BiqQuery is best for analyzing large
46314661
sets of data quickly, but it is not a direct replacement for a transactional database.
46324662

4663+
.. _io.bigquery_create_tables:
4664+
46334665
Creating BigQuery Tables
46344666
''''''''''''''''''''''''
46354667

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

4694+
46624695
.. _io.stata:
46634696

46644697
Stata Format

doc/source/whatsnew/v0.20.0.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,3 +80,5 @@ Performance Improvements
8080

8181
Bug Fixes
8282
~~~~~~~~~
83+
84+
- The :func:`pandas.io.gbq.to_gbq` method now stores ``INTEGER`` columns as ``dtype=object`` if they contain ``NULL`` values. Othewise they are stored as ``int64``. This prevents precision lost for integers greather than 2**53. Furthermore ``FLOAT`` columns with values above 10**4 are no more casted to ``int64`` which also caused precision lost (:issue: `14064`).

pandas/io/gbq.py

Lines changed: 13 additions & 11 deletions
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)