Skip to content

Commit f97fcdb

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 e27b296 commit f97fcdb

File tree

5 files changed

+197
-61
lines changed

5 files changed

+197
-61
lines changed

doc/source/install.rst

+5-8
Original file line numberDiff line numberDiff line change
@@ -250,9 +250,9 @@ Optional Dependencies
250250
* `Feather Format <https://github.com/wesm/feather>`__: necessary for feather-based storage, version 0.3.1 or higher.
251251
* `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:
252252

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

257257
* `matplotlib <http://matplotlib.org/>`__: for plotting
258258
* For Excel I/O:
@@ -272,11 +272,8 @@ Optional Dependencies
272272
<http://www.vergenet.net/~conrad/software/xsel/>`__, or `xclip
273273
<https://github.com/astrand/xclip/>`__: necessary to use
274274
:func:`~pandas.read_clipboard`. Most package managers on Linux distributions will have ``xclip`` and/or ``xsel`` immediately available for installation.
275-
* Google's `python-gflags <<https://github.com/google/python-gflags/>`__ ,
276-
`oauth2client <https://github.com/google/oauth2client>`__ ,
277-
`httplib2 <http://pypi.python.org/pypi/httplib2>`__
278-
and `google-api-python-client <http://github.com/google/google-api-python-client>`__
279-
: Needed for :mod:`~pandas.io.gbq`
275+
* For Google BigQuery I/O - see :ref:`here <io.bigquery_deps>`.
276+
280277
* `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.
281278
* One of the following combinations of libraries is needed to use the
282279
top-level :func:`~pandas.read_html` function:

doc/source/io.rst

+47-14
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ object.
3939
* :ref:`read_json<io.json_reader>`
4040
* :ref:`read_msgpack<io.msgpack>` (experimental)
4141
* :ref:`read_html<io.read_html>`
42-
* :ref:`read_gbq<io.bigquery_reader>` (experimental)
42+
* :ref:`read_gbq<io.bigquery>` (experimental)
4343
* :ref:`read_stata<io.stata_reader>`
4444
* :ref:`read_sas<io.sas_reader>`
4545
* :ref:`read_clipboard<io.clipboard>`
@@ -55,7 +55,7 @@ The corresponding ``writer`` functions are object methods that are accessed like
5555
* :ref:`to_json<io.json_writer>`
5656
* :ref:`to_msgpack<io.msgpack>` (experimental)
5757
* :ref:`to_html<io.html>`
58-
* :ref:`to_gbq<io.bigquery_writer>` (experimental)
58+
* :ref:`to_gbq<io.bigquery>` (experimental)
5959
* :ref:`to_stata<io.stata_writer>`
6060
* :ref:`to_clipboard<io.clipboard>`
6161
* :ref:`to_pickle<io.pickle>`
@@ -4556,16 +4556,11 @@ DataFrame with a shape and data types derived from the source table.
45564556
Additionally, DataFrames can be inserted into new BigQuery tables or appended
45574557
to existing tables.
45584558

4559-
You will need to install some additional dependencies:
4560-
4561-
- Google's `python-gflags <https://github.com/google/python-gflags/>`__
4562-
- `httplib2 <http://pypi.python.org/pypi/httplib2>`__
4563-
- `google-api-python-client <http://github.com/google/google-api-python-client>`__
4564-
45654559
.. warning::
45664560

45674561
To use this module, you will need a valid BigQuery account. Refer to the
4568-
`BigQuery Documentation <https://cloud.google.com/bigquery/what-is-bigquery>`__ for details on the service itself.
4562+
`BigQuery Documentation <https://cloud.google.com/bigquery/what-is-bigquery>`__
4563+
for details on the service itself.
45694564

45704565
The key functions are:
45714566

@@ -4579,7 +4574,44 @@ The key functions are:
45794574

45804575
.. currentmodule:: pandas
45814576

4582-
.. _io.bigquery_reader:
4577+
4578+
Supported Data Types
4579+
++++++++++++++++++++
4580+
4581+
Pandas supports all these `BigQuery data types <https://cloud.google.com/bigquery/data-types>`__:
4582+
``STRING``, ``INTEGER`` (64bit), ``FLOAT`` (64 bit), ``BOOLEAN`` and
4583+
``TIMESTAMP`` (microsecond precision). Data types ``BYTES`` and ``RECORD``
4584+
are not supported.
4585+
4586+
Integer and boolean ``NA`` handling
4587+
+++++++++++++++++++++++++++++++++++
4588+
4589+
.. versionadded:: 0.19
4590+
4591+
Since all columns in BigQuery queries are nullable, and NumPy lacks of ``NA``
4592+
support for integer and boolean types, this module will store ``INTEGER`` or
4593+
``BOOLEAN`` columns with at least one ``NULL`` value as ``dtype=object``.
4594+
Otherwise those columns will be stored as ``dtype=int64`` or ``dtype=bool``
4595+
respectively.
4596+
4597+
This is opposite to default pandas behaviour which will promote integer
4598+
type to float in order to store NAs. See the :ref:`gotchas<gotchas.intna>`
4599+
for detailed explaination.
4600+
4601+
While this trade-off works well for most cases, it breaks down for storing
4602+
values greater than 2**53. Such values in BigQuery can represent identifiers
4603+
and unnoticed precision lost for identifier is what we want to avoid.
4604+
4605+
.. _io.bigquery_deps:
4606+
4607+
Dependencies
4608+
++++++++++++
4609+
4610+
This module requires following additional dependencies:
4611+
4612+
- `httplib2 <https://github.com/httplib2/httplib2>`__: HTTP client
4613+
- `google-api-python-client <http://github.com/google/google-api-python-client>`__: Google's API client
4614+
- `oauth2client <https://github.com/google/oauth2client>`__: authentication and authorization for Google's API
45834615

45844616
.. _io.bigquery_authentication:
45854617

@@ -4594,7 +4626,7 @@ Is possible to authenticate with either user account credentials or service acco
45944626
Authenticating with user account credentials is as simple as following the prompts in a browser window
45954627
which will be automatically opened for you. You will be authenticated to the specified
45964628
``BigQuery`` account using the product name ``pandas GBQ``. It is only possible on local host.
4597-
The remote authentication using user account credentials is not currently supported in Pandas.
4629+
The remote authentication using user account credentials is not currently supported in pandas.
45984630
Additional information on the authentication mechanism can be found
45994631
`here <https://developers.google.com/identity/protocols/OAuth2#clientside/>`__.
46004632

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

4606-
You will need to install an additional dependency: `oauth2client <https://github.com/google/oauth2client>`__.
4607-
46084638
Authentication via ``application default credentials`` is also possible. This is only valid
46094639
if the parameter ``private_key`` is not provided. This method also requires that
46104640
the credentials can be fetched from the environment the code is running in.
@@ -4624,6 +4654,7 @@ Additional information on
46244654
A private key can be obtained from the Google developers console by clicking
46254655
`here <https://console.developers.google.com/permissions/serviceaccounts>`__. Use JSON key type.
46264656

4657+
.. _io.bigquery_reader:
46274658

46284659
Querying
46294660
''''''''
@@ -4667,7 +4698,6 @@ destination DataFrame as well as a preferred column order as follows:
46674698

46684699
.. _io.bigquery_writer:
46694700

4670-
46714701
Writing DataFrames
46724702
''''''''''''''''''
46734703

@@ -4757,6 +4787,8 @@ For example:
47574787
often as the service seems to be changing and evolving. BiqQuery is best for analyzing large
47584788
sets of data quickly, but it is not a direct replacement for a transactional database.
47594789

4790+
.. _io.bigquery_create_tables:
4791+
47604792
Creating BigQuery Tables
47614793
''''''''''''''''''''''''
47624794

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

4821+
47894822
.. _io.stata:
47904823

47914824
Stata Format

doc/source/whatsnew/v0.20.0.txt

+2
Original file line numberDiff line numberDiff line change
@@ -321,3 +321,5 @@ Bug Fixes
321321
- Require at least 0.23 version of cython to avoid problems with character encodings (:issue:`14699`)
322322
- Bug in converting object elements of array-like objects to unsigned 64-bit integers (:issue:`4471`)
323323
- Bug in ``pd.pivot_table()`` where no error was raised when values argument was not in the columns (:issue:`14938`)
324+
- The :func:`pandas.io.gbq.read_gbq` method now stores ``INTEGER`` columns as ``dtype=object`` if they contain ``NULL`` values. Otherwise 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`).
325+

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)