将两个json键值paris合并到Python中的新键值对中

时间:2015-12-10 03:49:48

标签: python json pandas

因此,基于一些反馈,我已经扩展了一些代码,因为我实际上正在采用更大的csv并首先对其进行转换。我试图输出的实际上是转换 - 相关代码:

def doThings(infile, outfile):
    f = pd.read_csv(infile)
    hmCols = {"timestamp": [], "value": []}    
for i, row in f.iterrows():
    total = row["Playspace_1"] + row["Playspace_2"] + row["Playspace_3"] + row["Playspace_4"]
    hmCols["timestamp"].append(row["Timestamp"])
    hmCols["value"].append(total)


pd.DataFrame(hmCols).to_json(outfile, orient="records")
doThings("test.csv", "heatmapData.json")

现在输出为:

[{"timestamp":1417982808063,"value":1},{"timestamp":1417982808063,"value":1},{"timestamp":1417982808753,"value":1},{"timestamp":1417982811944,"value":1}...]

我需要的是:

[{"1417982808063":1},{"1417982808063":1},{"1417982808753":1},{"1417982811944":1}...]

任何有关如何进行此转换的帮助都将不胜感激

2 个答案:

答案 0 :(得分:0)

...只需使用csv.reader

  f = csv.reader(some_file_handle)
  next(f) #skip header
  json.dump(dict((row[0],sum(map(int,row[1:]))) for row in f),open("output.json","wb"))  

我认为至少......没有测试

这假设in_file.csv看起来像

timestamp,Playspace_1,Playspace_2,Playspace_3,Playspace_4
123      ,0          ,1          ,0          ,0
....

(我根据您对原始问题的评论取消了这个答案)

如果你真的和熊猫结婚了,我想你可以做点什么

totals = f["Playspace_1"] + f["Playspace_2"] + f["Playspace_3"] + f["Playspace_4"]
json.dump(dict(zip(f["timestamp"],totals),open("out.json","wb")))

答案 1 :(得分:0)

dic_in = [
    {"timestamp":1417982808063,"value":1},
    {"timestamp":1417982808063,"value":1},
    {"timestamp":1417982808753,"value":1},
    {"timestamp":1417982811944,"value":1}
]

dic_out = [{i['timestamp']: i['value']} for i in dic_in]