【发布时间】:2014-03-20 03:39:52
【问题描述】:
我刚刚安装了 pandas 和 numpy,对它们没有任何经验。我正在尝试获取类似于您需要传递给 Google BigQuery 的 json 数据结构。 https://developers.google.com/bigquery/docs/reference/v2/jobs#configuration.load.encoding
目标
- 确定数据类型
- 返回
JSON,其中键是列名,值是数据类型之一:STRING, INTEGER, FLOAT, BOOLEAN, TIMESTAMP or RECORD
我尝试过的
import numpy as np
import pandas as pd
import config
import boto
from StringIO import StringIO
k = boto.connect_s3(**config.AWS_PARAMS).get_bucket('xxxxxxx').get_key('DATA.csv')
o = StringIO(k.get_contents_as_string())
df = pd.read_csv(o)
def map_dtype(dtype):
if dtype.kind == 'i':
# [int8, int16, int32, int64]
return "INTEGER"
elif dtype.kind == 'u':
# [uint8, uint16, uint32, uint64]
return "INTEGER"
else:
return "STRING"
fields = []
for c, d in zip(df.columns, df.dtypes):
field = {}
field['type'] = map_dtype(d)
field['name'] = c
fields.append(field)
print fields
结果
[{'type': 'INTEGER', 'name': 'VALUE'}, {'type': 'INTEGER', 'name': 'ID'}, {'type': 'STRING', 'name': 'Key'}, {'type': 'STRING', 'name': 'EmailAddress'}]
如您所见,我得到了正确的结果。但我不喜欢我的做法。我觉得有一种更简单的方法可以做到这一点。
我想改进的地方
-
map_dtype()函数,如您所见,我必须在 BigQuery 中使用字符串表示手动映射数据类型 -
For each loop,感觉应该有一种更简单的方法可以将 data_type 分配给列。
【问题讨论】:
标签: python numpy pandas google-bigquery