在自定义输出数据格式时,出现了这个一个问题。每天获得的数据类型为字典型,具体如下:
{'keyword': '第一个', 'date': '2019-01-01', 'index': '234'}
{'keyword': '第一个', 'date': '2019-01-02', 'index': '235'}
{'keyword': '第二个', 'date': '2019-01-01', 'index': '223'}
{'keyword': '第二个', 'date': '2019-01-02', 'index': '224'}
想要的目标格式为:
于是需要自定义函数将字典型数据整理成想要的格式,代码如下:
df = pd.DataFrame()
def write_file(df, diction):
keyword = diction['keyword']
date = diction['date']
column = df.columns.values.tolist()
if keyword not in column:
column.append(keyword)
df[keyword] = 0
df.loc[date,keyword] = diction['index']
return df
for x in data:
res = write_file(df,x)
print(res)
#将结果写入CSV文件中
#res.to_csv('exam.csv', encoding ='utf-8-sig' )
运行结果:
第一个 第二个
2019-01-01 234 223
2019-01-02 235 224