Skip to content

Use general float format when writing to CSV buffer to prevent numerical overload #193

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jul 26, 2018
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pandas_gbq/load.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def encode_chunk(dataframe):
csv_buffer = six.StringIO()
dataframe.to_csv(
csv_buffer, index=False, header=False, encoding='utf-8',
date_format='%Y-%m-%d %H:%M:%S.%f')
float_format='%.15g', date_format='%Y-%m-%d %H:%M:%S.%f')

# Convert to a BytesIO buffer so that unicode text is properly handled.
# See: https://github.com/pydata/pandas-gbq/issues/106
Expand Down
15 changes: 15 additions & 0 deletions tests/unit/test_load.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import pandas

from pandas_gbq import load
from io import StringIO


def test_encode_chunk_with_unicode():
Expand All @@ -20,6 +21,20 @@ def test_encode_chunk_with_unicode():
assert u'信用卡' in csv_string


def test_encode_chunk_with_floats():
"""Test that floats in a dataframe are encoded with at most 15 significant
figures.

See: https://github.com/pydata/pandas-gbq/issues/192
"""
input_csv = StringIO('01/01/17 23:00,1.05148,1.05153,1.05148,1.05153,4')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For Py2 to pass, you need to put StringIO(u'...') to pass unicode into StringIO (you can see the test failure in Travis)

df = pandas.read_csv(input_csv, header=None)
csv_buffer = load.encode_chunk(df)
csv_bytes = csv_buffer.read()
csv_string = csv_bytes.decode('utf-8')
assert '1.05153' in csv_string


def test_encode_chunks_splits_dataframe():
df = pandas.DataFrame(numpy.random.randn(6, 4), index=range(6))
chunks = list(load.encode_chunks(df, chunksize=2))
Expand Down