gpt4 book ai didi

python - 数据框到json文件

转载 作者:太空宇宙 更新时间:2023-11-03 12:01:10 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com