Pandas:将数据帧写入 json 并拆分

Pandas: Write dataframe to json with split

我需要将数据写入 json。问题是我无法为字符串建立定界符。 我的 df 看起来像

     id       date  val
0   123 2015-12-12    1
1   123 2015-12-13    1
2   123 2015-12-14    0
3   123 2015-12-15    1
4   123 2015-12-16    1
5   123 2015-12-17    0
6   123 2015-12-18    1
7   456 2015-12-12    1
8   456 2015-12-13    1
9   456 2015-12-14    0
10  456 2015-12-15    1

我用

df.groupby('id').apply(lambda x: x.set_index('date')['val'].to_dict()).to_json('nielsen', orient='index')

我想得到像

这样的东西
{
"1234567890abcdef1234567890abcdef": {
    "2016-06": 1, 
    "2016-05": 0, 
    "2016-04": 0, 
    "2016-03": 1, 
    "2016-02": 1, 
    "2016-01": 0
}, 
"0987654321abcdef1234567890abcdef": {
    "2016-06": 1, 
    "2016-05": 1, 
    "2016-04": 1, 
    "2016-03": 0, 
    "2016-02": 0, 
    "2016-01": 0
}
}

我该怎么做?

您可以 to_json 写入 StringIO 对象,然后使用 json loads/dumps 根据您的喜好格式化:

import pandas as pd
import StringIO, json
df = pd.read_csv('data.csv')
nielson = StringIO.StringIO()
df.groupby('id').apply(lambda x: x.set_index('date')['val'].to_dict()).to_json(nielson, orient='index')
print(json.dumps(json.loads(nielson.getvalue()),indent=2))

这会产生:

{
  "123": {
    "2015-12-14": 0, 
    "2015-12-15": 1, 
    "2015-12-16": 1, 
    "2015-12-17": 0, 
    "2015-12-12": 1, 
    "2015-12-13": 1, 
    "2015-12-18": 1
  }, 
  "456": {
    "2015-12-14": 0, 
    "2015-12-15": 1, 
    "2015-12-12": 1, 
    "2015-12-13": 1
  }
}

有关其他格式选项,请参阅 help(json.dumps)。 有关如何写入文件的详细信息,请参阅 help(json.dump)(基本示例如下所示):

with open('nielsen','w') as f:
    json.dump(json.loads(nielson.getvalue()), f, indent=2)