是否有一种有效的方法来创建分层JSON(n级深度),其中父值是键而不是变量标签?即:
{"2017-12-31":
{"Junior":
{"Electronics":
{"A":
{"sales": 0.440755
}
},
{"B":
{"sales": -3.230951
}
}
}, ...etc...
}, ...etc...
}, ...etc...
1。我的测试DataFrame:
colIndex=pd.MultiIndex.from_product([['New York','Paris'],
['Electronics','Household'],
['A','B','C'],
['Junior','Senior']],
names=['City','Department','Team','Job Role'])
rowIndex=pd.date_range('25-12-2017',periods=12,freq='D')
df1=pd.DataFrame(np.random.randn(12, 24), index=rowIndex, columns=colIndex)
df1.index.name='Date'
df2=df1.resample('M').sum()
df3=df2.stack(level=0).groupby('Date').sum()
2。我正在进行转型,因为它似乎是构建JSON的最合理的结构:
df4=df3.stack(level=[0,1,2]).reset_index() \
.set_index(['Date','Job Role','Department','Team']) \
.sort_index()
第3。我的尝试 - 迄今为止
我遇到了这个very helpful SO question,它使用以下代码解决了一级嵌套的问题:
j =(df.groupby(['ID','Location','Country','Latitude','Longitude'],as_index=False) \
.apply(lambda x: x[['timestamp','tide']].to_dict('r'))\
.reset_index()\
.rename(columns={0:'Tide-Data'})\
.to_json(orient='records'))
...但我无法找到让嵌套.groupby()
工作的方法:
j=(df.groupby('date', as_index=True).apply(
lambda x: x.groupby('Job Role', as_index=True).apply(
lambda x: x.groupby('Department', as_index=True).apply(
lambda x: x.groupby('Team', as_index=True).to_dict()))) \
.reset_index().rename(columns={0:'sales'}).to_json(orient='records'))
答案 0 :(得分:5)
您可以使用itertuples生成嵌套的dict
,然后转储到json
。为此,您需要将日期时间戳更改为string
df4=df3.stack(level=[0,1,2]).reset_index()
df4['Date'] = df4['Date'].dt.strftime('%Y-%m-%d')
df4 = df4.set_index(['Date','Job Role','Department','Team']) \
.sort_index()
创建嵌套字典
def nested_dict():
return collections.defaultdict(nested_dict)
result = nested_dict()
使用itertuples
填充
for row in df4.itertuples():
result[row.Index[0]][row.Index[1]][row.Index[2]][row.Index[3]]['sales'] = row._1
# print(row)
然后使用json
模块转储它。
import json
json.dumps(result)
'{“2017-12-31”:{“Junior”:{“Electronics”:{“A”:{“sales”: - 0.3947134370101142},“B”:{“sales”: - 0.9873530754403204}, “C”:{“sales”: - 1.1182598058984508}},“Household”:{“A”:{“sales”: - 1.112850078098677},“B”:{“sales”:2.0330914483907847},“C”:{“销售“:3.94762379718749}}},”高级“:{”电子“:{”A“:{”销售“:1.4528493451404196},”B“:{”销售“: - 2.3277322345261005},”C“:{”销售“: - - 2.8040263791743922}},”住户“:{”A“:{”sales“:3.0972591929279663},”B“:{”sales“:9.884565742502392},”C“:{”sales“:2.9359830722457576}}}} ,“2018-01-31”:{“Junior”:{“Electronics”:{“A”:{“sales”: - 1.3580300149125217},“B”:{“sales”:1.414665000013205},“C”:{ “sales”: - 1.432795129108244}},“Household”:{“A”:{“sales”:2.7783259569115346},“B”:{“sales”:2.717700275321333},“C”:{“sales”:1.4358377416259644}} },“Senior”:{“Electronics”:{“A”:{“sales”:2.8981726774941485},“B”:{“sales”:12.022897003654117},“C”:{“sales”:0.01776855733076088}},“家庭“:{”A“:{”sales“:-3.3421637766130 92},“B”:{“sales”:-5.283208386572307},“C”:{“sales”:2.942580121975619}}}}}'
答案 1 :(得分:1)
我遇到了这个问题,并且对OP设置的复杂性感到困惑。这是一个最小的示例和解决方案(基于@MaartenFabré提供的答案)。
import collections
import pandas as pd
# build init DF
x = ['a', 'a']
y = ['b', 'c']
z = [['d'], ['e', 'f']]
df = pd.DataFrame(list(zip(x, y, z)), columns=['x', 'y', 'z'])
# x y z
# 0 a b [d]
# 1 a c [e, f]
设置常规索引,平面索引,然后使之成为多索引
# set flat index
df = df.set_index(['x', 'y'])
# set up multi index
df = df.reindex(pd.MultiIndex.from_tuples(zip(x, y)))
# z
# a b [d]
# c [e, f]
然后初始化一个嵌套字典,然后逐项填写
nested_dict = collections.defaultdict(dict)
for keys, value in df.z.iteritems():
nested_dict[keys[0]][keys[1]] = value
# defaultdict(dict, {'a': {'b': ['d'], 'c': ['e', 'f']}})
此时,您可以JSON转储它,等等。