-
Notifications
You must be signed in to change notification settings - Fork 125
BUG: Fix uploading of dataframes containing int64 and float64 columns #117
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
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
616d306
BUG: Fix uploading of dataframes containing int64 and float64 columns
tswast 64ff345
ENH: allow chunksize=None to disable chunking in to_gbq()
tswast f6bb63d
TST: update min g-c-bq lib to 0.29.0 in CI
tswast da4ddec
BUG: pass schema to load job for to_gbq
tswast 8d820ed
Generate schema if needed for table creation.
tswast b8c933d
Restore _generate_bq_schema, as it is used in tests.
tswast 1ce8b0b
Add fixes to changelog.
tswast File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,4 @@ | ||
google-auth==1.0.0 | ||
google-auth-oauthlib==0.0.1 | ||
mock | ||
google-cloud-bigquery==0.28.0 | ||
google-cloud-bigquery==0.29.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
"""Helper methods for loading data into BigQuery""" | ||
|
||
from google.cloud import bigquery | ||
import six | ||
|
||
from pandas_gbq import _schema | ||
|
||
|
||
def encode_chunk(dataframe): | ||
"""Return a file-like object of CSV-encoded rows. | ||
|
||
Args: | ||
dataframe (pandas.DataFrame): A chunk of a dataframe to encode | ||
""" | ||
csv_buffer = six.StringIO() | ||
dataframe.to_csv( | ||
csv_buffer, index=False, header=False, encoding='utf-8', | ||
date_format='%Y-%m-%d %H:%M') | ||
|
||
# Convert to a BytesIO buffer so that unicode text is properly handled. | ||
# See: https://github.com/pydata/pandas-gbq/issues/106 | ||
body = csv_buffer.getvalue() | ||
if isinstance(body, bytes): | ||
body = body.decode('utf-8') | ||
body = body.encode('utf-8') | ||
return six.BytesIO(body) | ||
|
||
|
||
def encode_chunks(dataframe, chunksize=None): | ||
dataframe = dataframe.reset_index(drop=True) | ||
if chunksize is None: | ||
yield 0, encode_chunk(dataframe) | ||
return | ||
|
||
remaining_rows = len(dataframe) | ||
total_rows = remaining_rows | ||
start_index = 0 | ||
while start_index < total_rows: | ||
end_index = start_index + chunksize | ||
chunk_buffer = encode_chunk(dataframe[start_index:end_index]) | ||
start_index += chunksize | ||
remaining_rows = max(0, remaining_rows - chunksize) | ||
yield remaining_rows, chunk_buffer | ||
|
||
|
||
def load_chunks( | ||
client, dataframe, dataset_id, table_id, chunksize=None, schema=None): | ||
destination_table = client.dataset(dataset_id).table(table_id) | ||
job_config = bigquery.LoadJobConfig() | ||
job_config.write_disposition = 'WRITE_APPEND' | ||
job_config.source_format = 'CSV' | ||
|
||
if schema is None: | ||
schema = _schema.generate_bq_schema(dataframe) | ||
|
||
# Manually create the schema objects, adding NULLABLE mode | ||
# as a workaround for | ||
# https://github.com/GoogleCloudPlatform/google-cloud-python/issues/4456 | ||
for field in schema['fields']: | ||
if 'mode' not in field: | ||
field['mode'] = 'NULLABLE' | ||
|
||
job_config.schema = [ | ||
bigquery.SchemaField.from_api_repr(field) | ||
for field in schema['fields'] | ||
] | ||
|
||
chunks = encode_chunks(dataframe, chunksize=chunksize) | ||
for remaining_rows, chunk_buffer in chunks: | ||
yield remaining_rows | ||
client.load_table_from_file( | ||
chunk_buffer, | ||
destination_table, | ||
job_config=job_config).result() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
"""Helper methods for BigQuery schemas""" | ||
|
||
|
||
def generate_bq_schema(dataframe, default_type='STRING'): | ||
"""Given a passed dataframe, generate the associated Google BigQuery schema. | ||
|
||
Arguments: | ||
dataframe (pandas.DataFrame): D | ||
default_type : string | ||
The default big query type in case the type of the column | ||
does not exist in the schema. | ||
""" | ||
|
||
type_mapping = { | ||
'i': 'INTEGER', | ||
'b': 'BOOLEAN', | ||
'f': 'FLOAT', | ||
'O': 'STRING', | ||
'S': 'STRING', | ||
'U': 'STRING', | ||
'M': 'TIMESTAMP' | ||
} | ||
|
||
fields = [] | ||
for column_name, dtype in dataframe.dtypes.iteritems(): | ||
fields.append({'name': column_name, | ||
'type': type_mapping.get(dtype.kind, default_type)}) | ||
|
||
return {'fields': fields} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
# -*- coding: utf-8 -*- | ||
|
||
import numpy | ||
import pandas | ||
|
||
|
||
def test_encode_chunk_with_unicode(): | ||
"""Test that a dataframe containing unicode can be encoded as a file. | ||
|
||
See: https://github.com/pydata/pandas-gbq/issues/106 | ||
""" | ||
from pandas_gbq._load import encode_chunk | ||
|
||
df = pandas.DataFrame( | ||
numpy.random.randn(6, 4), index=range(6), columns=list('ABCD')) | ||
df['s'] = u'信用卡' | ||
csv_buffer = encode_chunk(df) | ||
csv_bytes = csv_buffer.read() | ||
csv_string = csv_bytes.decode('utf-8') | ||
assert u'信用卡' in csv_string | ||
|
||
|
||
def test_encode_chunks_splits_dataframe(): | ||
from pandas_gbq._load import encode_chunks | ||
df = pandas.DataFrame(numpy.random.randn(6, 4), index=range(6)) | ||
chunks = list(encode_chunks(df, chunksize=2)) | ||
assert len(chunks) == 3 | ||
remaining, buffer = chunks[0] | ||
assert remaining == 4 | ||
assert len(buffer.readlines()) == 2 | ||
|
||
|
||
def test_encode_chunks_with_chunksize_none(): | ||
from pandas_gbq._load import encode_chunks | ||
df = pandas.DataFrame(numpy.random.randn(6, 4), index=range(6)) | ||
chunks = list(encode_chunks(df)) | ||
assert len(chunks) == 1 | ||
remaining, buffer = chunks[0] | ||
assert remaining == 0 | ||
assert len(buffer.readlines()) == 6 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
|
||
import datetime | ||
|
||
import pandas | ||
import pytest | ||
|
||
from pandas_gbq import _schema | ||
|
||
|
||
@pytest.mark.parametrize( | ||
'dataframe,expected_schema', | ||
[ | ||
( | ||
pandas.DataFrame(data={'col1': [1, 2, 3]}), | ||
{'fields': [{'name': 'col1', 'type': 'INTEGER'}]}, | ||
), | ||
( | ||
pandas.DataFrame(data={'col1': [True, False]}), | ||
{'fields': [{'name': 'col1', 'type': 'BOOLEAN'}]}, | ||
), | ||
( | ||
pandas.DataFrame(data={'col1': [1.0, 3.14]}), | ||
{'fields': [{'name': 'col1', 'type': 'FLOAT'}]}, | ||
), | ||
( | ||
pandas.DataFrame(data={'col1': [u'hello', u'world']}), | ||
{'fields': [{'name': 'col1', 'type': 'STRING'}]}, | ||
), | ||
( | ||
pandas.DataFrame(data={'col1': [datetime.datetime.now()]}), | ||
{'fields': [{'name': 'col1', 'type': 'TIMESTAMP'}]}, | ||
), | ||
( | ||
pandas.DataFrame( | ||
data={ | ||
'col1': [datetime.datetime.now()], | ||
'col2': [u'hello'], | ||
'col3': [3.14], | ||
'col4': [True], | ||
'col5': [4], | ||
}), | ||
{ | ||
'fields': [ | ||
{'name': 'col1', 'type': 'TIMESTAMP'}, | ||
{'name': 'col2', 'type': 'STRING'}, | ||
{'name': 'col3', 'type': 'FLOAT'}, | ||
{'name': 'col4', 'type': 'BOOLEAN'}, | ||
{'name': 'col5', 'type': 'INTEGER'}, | ||
], | ||
}, | ||
), | ||
]) | ||
def test_generate_bq_schema(dataframe, expected_schema): | ||
schema = _schema.generate_bq_schema(dataframe) | ||
assert schema == expected_schema |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
FYI this file name currently has two underscores
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks. I'm aware. I'm following the convention that the filename should be
test_
+ the filename of the file under test.