gpt4 book ai didi

Python pandas to_json() 格式无效

转载 作者:行者123 更新时间:2023-11-28 22:47:51 31 4
gpt4 key购买 nike

我在处理 JSON 字符串输出时遇到问题。我正在使用制表符分隔的 CSV 文件,它看起来像这样:

date        time        loc_id  country name    sub1_id sub2_id type
2014-09-11 00:00:01 179 US acmnj 269 382 ico
2014-09-11 00:00:01 179 US acmnj 269 382 ico
2014-09-11 00:00:01 179 GB acmnj 269 382 ico
2014-09-11 00:00:01 179 US acmnj 269 382 ico
2014-09-11 00:00:02 179 GB acmnj 269 383 ico
2014-09-11 00:00:02 179 JP acmnj 269 383 ico

代码如下所示:

df = pd.read_csv('log.csv',sep='\t',encoding='utf-16')
count = df.groupby(['country','name','sub1_id','sub2_id','type']).size()
print(count.order(na_position='last',ascending=False).to_frame().to_json(orient='index'))

输出看起来像这样(前几行):

{"["US","acmnj",269,383,"ico"]":{"0":76174},"["US","acmnj",269,382,"ico"]":{"0":73609},"["IT","acmnj",269,383,"ico"]":{"0":54211},"["IT","acmnj",269,382,"ico"]":{"0":52398},"["GB","acmnj",269,383,"ico"]":{"0":41346},"["GB","acmnj",269,382,"ico"]":{"0":40140},"["US","acmnj",269,405,"ico"]":{"0":39482},"["US","acmnj",269,400 ,"ico"]":{"0":39303},"["US","popcdd",178,365,"ico"]":{"0":33168},"["IT","acmnj",269,400,"ico"]":{"0":33026},"["IT","acmnj",269,405,"ico"]":{"0":32824},"["IT","achrfb141",141,42,"ico"]":{"0":26986},"["GB","acmnj",269,405,"ico"]":{"0":25895},"["IN","acmnj",269,383,"ico"]":{"0":25647},"["GB","acmnj",269,400,"ico"]":{"0":25488...

我想在 PHP 中加载此输出,但在我尝试对其进行解码时得到 NULL。我使用 JSON Validator 来检查字符串,它是无效的。我也尝试过不使用 orient 参数,但得到无效的 JSON 格式。

最佳答案

这似乎是 Pandas 的问题。我重现了你的错误。

DataFrame.to_json 可以接受几个不同的orient 参数:'split'、'records'、'index'、'columns' 和 'values'。

在您的情况下,“split”、“records”和“values”似乎有效,但“index”和“columns”无效。

您可以使用 json 模块在 python 中快速测试它:

df = pd.read_csv('log.csv',sep='\t',encoding='utf-16')
count = df.groupby(['country','name','sub1_id','sub2_id','type']).size()
f=count.order(ascending=False).to_frame()
json.loads(f.to_json(orient='index')) # This failed for me
json.loads(f.to_json(orient='records')) #This worked

关于Python pandas to_json() 格式无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25810587/

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