我使用vertica_python从数据库中提取数据。我提取的列以字符串形式出现,格式如下:
[{"id":0,"prediction_type":"CONV_PROBABILITY","calibration_factor":0.906556,"inte cept":-2.410414,"advMatchTypeId":-0.239877,"atsId":-0.135568,"deviceTypeId":0.439130,"dmaCode":-0.251728,"keywordId":0.442240}]
然后,我将这个sting拆分并解析,并以以下格式将其加载到excel中,每个索引都是一个单元格:
^{pr2}$这是我的问题。那个字符串没有一个明确的格式,这意味着,有时我会丢失字符串中的某些功能,从而弄乱了我的格式。下面是一个例子:
intercept -2.41041 advMatchTypeId -0.23987 deviceTypeId 0.37839 dmaCode -0.53552 keywordId 0.44224
intercept -2.41041 advMatchTypeId -0.23987 atsId 0.80708 deviceTypeId -0.19573 dmaCode -0.69982 keywordId 0.44224
我怎样才能保留我想要的格式,并让上面的例子变成这样:
intercept -2.41041 advMatchTypeId -0.23987 deviceTypeId 0.37839 dmaCode -0.53552 keywordId 0.44224
intercept -2.41041 advMatchTypeId -0.23987 atsId 0.80708 deviceTypeId -0.19573 dmaCode -0.69982 keywordId 0.44224
这是我使用的代码:
data_all = cur.fetchall()
for i in range(len(data_all)):
col = 0
data_one = ''.join(data_all[i])
raw_coef = data_one.split(',')[1:len(data_all)]
for j in range(len(raw_coef)):
raw = ''.join(raw_coef[j])
raw = re.sub('"|}|{|[|]|', '', raw)[:-1]
raw = raw.split(":")
for k in range(len(raw)):
worksheet.write(i, col, raw[k], align_left)
feature.append(raw[0]) # for unique values
col+=1
我的疑问:
cur.execute(
"""
select MODEL_COEF
from
dcf_funnel.ADV_BIDDER_PRICING_LOG
where MODEL_ID = 8960
and DATE(AMP_QUERY_TIMESTAMP) = '11-02-2016'
"""
)
您可以跳过所有解析并使用pandas:
如果查询结果已经是Python中的dict列表,那么它将把查询结果读入数据帧。在
^{pr2}$如果您真的有字符串,可以使用
read_json
:进一步的思考使我明白你的
data_all
实际上是一个dict列表的列表,类似于:在这种情况下,需要在传递到DataFrame之前连接列表:
这将以普通标题+值格式写入:
如果您的最终目标只是获得所有特性的方法,pandas可以直接使用任意数量的列,正确处理缺失值:
给予
注意歧义
在OP中,很难知道
data_all
的类型,因为您显示的片段在字面语法中看起来像一个dict列表,但是您会说“我拉的列是一个字符串”。在请注意以下IPython会话中输入的表示方式之间的差异:
相关问题 更多 >
编程相关推荐