python - 数据框到json文件

标签 python pandas

我想将数据框转换为 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/

相关文章:

python - 在 NLTK Python 的朴素贝叶斯分类器中使用文档长度

python - 移动行以及 Pandas 数据框中的索引

Python Pandas 数据框 : find max for each unique values of an another column

python - Python中集合的迭代顺序

python - 运行时错误: Task got Future <Future pending> attached to a different loop

python - 如何使用 pdfpages 将数据框添加到 pdf 文件

python - 虹膜数据集未显示 "Species"列

python Pandas : list of integers as individual values of DataFrame

python - 将字符串转换为日期时间 [hh :mm:ss]

python - 为什么在 django rest 框架中找不到我的 View ?