Python:将df写入json

时间:2016-08-17 22:25:53

标签: python json pandas dictionary

我有数据框

month                             2015-05  2015-06  2015-07  2015-08  2015-    09  \
ID                                                                              
00051f002f5a0c179d7ce191ca2c6401        0        0        0        1        1   
0011ec51ddb5a41abb2d451fdfa0996a        0        0        0        1        1   
0012ea90a6deb4eeb2924fb13e844136        1        1        1        1        1   
0014ff1f6a95d789d3be3df5249cfe2f        0        0        0        1        1   

我尝试将它写入json并获得像

一样的smth
{
  "123": {
    "2015-12-14": 0, 
    "2015-12-15": 1, 
    "2015-12-16": 1, 
    "2015-12-17": 0
  }, 
  "456": {
    "2015-12-14": 0, 
    "2015-12-15": 1, 
    "2015-12-12": 1, 
    "2015-12-13": 1
  }
}

但是我得到了

{
  "2015-05": {
    "00051f002f5a0c179d7ce191ca2c6401": 0, 
    "0011ec51ddb5a41abb2d451fdfa0996a": 0, 
    "0012ea90a6deb4eeb2924fb13e844136": 1, 
    "0014ff1f6a95d789d3be3df5249cfe2f": 0, 
    "0017fbf132aac12d0f9f3ecb9ee7813d": 0, ...

如何更改并获取第一个密钥ID?

1 个答案:

答案 0 :(得分:0)

尝试df.to_json(orient="index"),其中df是您的DataFrame对象。

例如,

In [32]: df
Out[32]: 
            a  b    c
deadbeef  foo  1  2.5
f005ba11  bar  3  4.5
7e1eca57  baz  5  6.5

In [33]: df.to_json(orient="index")
Out[33]: '{"deadbeef":{"a":"foo","b":1,"c":2.5},"f005ba11":{"a":"bar","b":3,"c":4.5},"7e1eca57":{"a":"baz","b":5,"c":6.5}}'

让我们跳过一些箍看到该字符串的格式很好的版本:

In [56]: s = df.to_json(orient="index")

In [57]: print(json.dumps(json.loads(s), indent=4))
{
    "deadbeef": {
        "a": "foo", 
        "c": 2.5, 
        "b": 1
    }, 
    "7e1eca57": {
        "a": "baz", 
        "c": 6.5, 
        "b": 5
    }, 
    "f005ba11": {
        "a": "bar", 
        "c": 4.5, 
        "b": 3
    }
}