我想将数据框转换为 json 文件。目前我的数据框看起来像这样:
a b
P1 7950
P2 1274
P3 6160
我想将此数据框转换为 json 文件,其中第一列的值是键,第二列的值是值:就像 {P1:7950, P2:1274, P3:6160)
我试过了,但它产生的输出格式不正确(不是我上面说的那种)
df.set_index('a').to_json()
最佳答案
首先用set_index
创建系列
然后 Series.to_json
:
j = df.set_index('a')['b'].to_json()
print (j)
{"P1":7950,"P2":1274,"P3":6160}
对于文件:
df.set_index('a')['b'].to_json(filename)
关于python - 数据框到json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48209914/