我有以下JSON格式,我需要将其转换为python中的数据帧。请让我知道,如何去做。
JSON:
User Patterns
[{"Jane": [{"Thermostat": 20, "Days": [1, 2], "Hour": 6, "Minute": 43}],
"John": [{"Thermostat": 18, "Days": [1, 2], "Hour": 0, "Minute": 15}],
"Jen": [{"Thermostat": 22, "Days": [1, 2], "Hour": 10, "Minute": 1}]}]
我希望我的数据框看起来像:
User Thermostat Days Hour Minute
Jane 20 [1,2] 6 43
John 18 [1,2] 0 15
Jen 22 [1,2] 10 1
答案 0 :(得分:4)
jstr = """[{"Jane": [{"Thermostat": 20, "Days": [1, 2], "Hour": 6, "Minute": 43}],
"John": [{"Thermostat": 18, "Days": [1, 2], "Hour": 0, "Minute": 15}],
"Jen": [{"Thermostat": 22, "Days": [1, 2], "Hour": 10, "Minute": 1}]}]"""
pd.DataFrame.from_dict(
{k: v[0] for k, v in json.loads(jstr)[0].items()}, 'index'
).rename_axis('User').reset_index()
如果您想拆分Days
列
df = pd.DataFrame.from_dict(
{k: v[0] for k, v in json.loads(jstr)[0].items()}, 'index'
).rename_axis('User').reset_index()
df.drop('Days', 1).join(
pd.DataFrame(df.Days.tolist()).rename(columns='Day{}'.format))
您可以将此功能化:
def read_my_json(jstr):
return pd.DataFrame.from_dict(
{k: v[0] for k, v in json.loads(jstr)[0].items()}, 'index'
).rename_axis('User').reset_index()