我从软件 API 检索数据(JSON 格式)并将其转换为数据帧以将其写入 CSV(pandas 库)。我会添加一列时间。我希望在第一行写“时间”,例如在以下行写“Fri Mar 29 09:16:02 2019”。关于如何实现这一目标的想法?我必须添加时间,但只是在数据框的第一行。import jsonimport pandas as pdimport timeimport urllib.requesturl='http://localhost:47800/api/v1/bacnet/devices/0/objects?properties=present-value&properties=object-name'req = urllib.request.Request(url)r = urllib.request.urlopen(req).read()data = json.loads(r.decode('utf-8'))time=time.asctime(time.localtime(time.time()))result = pd.io.json.json_normalize(data['objects'])result_tri = result.reindex(columns=[time,'object-name','present-value'])当前结果 Fri Mar 29 09:47:36 2019 object-name present-value0 NaN Température_1 0 660.01 NaN Humidité_1 1 497.02 NaN Pression_1 2 497.03 NaN Vitesse_Vent 3 497.04 NaN Luminosité 4 497.05 NaN Etat_Pompe 3 0.06 NaN Greisch_Simulator NaN7 NaN networkPort 30800 NaN想要的结果 Time object-name present-value0 Fri Mar 29 09:47:36 2019 Température_1 0 660.01 Fri Mar 29 09:47:36 2019 Humidité_1 1 497.02 Fri Mar 29 09:47:36 2019 Pression_1 2 497.03 Fri Mar 29 09:47:36 2019 Vitesse_Vent 3 497.04 Fri Mar 29 09:47:36 2019 Luminosité 4 497.05 Fri Mar 29 09:47:36 2019 Etat_Pompe 3 0.06 Fri Mar 29 09:47:36 2019 Greisch_Simulator NaN7 Fri Mar 29 09:47:36 2019 networkPort 30800 NaN
2 回答
眼眸繁星
TA贡献1873条经验 获得超9个赞
利用
result_tri = result.reindex(columns=['Time','object-name','present-value'])
result_tri['Time'] = time
慕妹3146593
TA贡献1820条经验 获得超9个赞
您可以直接在 df 中添加新列。
当你在做
result_tri = result.reindex(columns=[time,'object-name','present-value'])
**you actually doing**
result_tri = result.reindex(columns="Fri Mar 29 09:47:36 2019",'object-name','present-value']
time在您的方法中是可变的,它会被您分配给它的值替换。
你只需要做:
result = pd.io.json.json_normalize(data['objects'])
result["time"] = time.asctime(time.localtime(time.time()))
result = result.reindex(columns=['Time','object-name','present-value'])
添加回答
举报
0/150
提交
取消