Pandas 使用密钥将数据帧转换为json
我有一个列为['a'、'b'、'c'的数据框架 并希望在字典中导出如下内容:Pandas 使用密钥将数据帧转换为json,pandas,Pandas,我有一个列为['a'、'b'、'c'的数据框架 并希望在字典中导出如下内容: { 'value of a' : { 'b': 3, 'c': 7}, 'value2 of a' : { 'b': 7, 'c': 9} } 我相信你需要: 对于json使用: df = pd.DataFrame({'a':list('ABC'), 'b':[4,5,4], 'c':[7,8,9]}) print (df)
{ 'value of a' : { 'b': 3, 'c': 7},
'value2 of a' : { 'b': 7, 'c': 9}
}
我相信你需要:
对于json使用:
df = pd.DataFrame({'a':list('ABC'),
'b':[4,5,4],
'c':[7,8,9]})
print (df)
a b c
0 A 4 7
1 B 5 8
2 C 4 9
d = df.set_index('a').to_dict('index')
print (d)
{'A': {'b': 4, 'c': 7}, 'B': {'b': 5, 'c': 8}, 'C': {'b': 4, 'c': 9}}
j = df.set_index('a').to_json(orient='index')
print (j)
{"A":{"b":4,"c":7},"B":{"b":5,"c":8},"C":{"b":4,"c":9}}