pandas 无法使用 Python 将 JSON 文件转换为 CSV
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33590184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unable to convert JSON file to CSV using Python
提问by Tsing
I was trying to convert the below JSON file into a csv file.
我试图将以下 JSON 文件转换为 csv 文件。
JSON file
JSON 文件
[{
"SubmitID":1, "Worksheet":3, "UserID":65,
"Q1":"395",
"Q2":"2178",
"Q3":"2699",
"Q4":"1494"},{
"SubmitID":2, "Worksheet":3, "UserID":65,
"Q4":"1394"},{
"SubmitID":3, "Worksheet":4, "UserID":65,
"Q1":"1629",
"Q2":"1950",
"Q3":"0117",
"Q4":"1816",
"Empty":" "}]
However, my Python code below gives the error message "TypeError: Expected String or Unicode". May I know how should I modify my program to make it work?
但是,我下面的 Python 代码给出了错误消息“TypeError: Expected String or Unicode”。我可以知道我应该如何修改我的程序以使其工作吗?
import json
import pandas as pd
f2 = open('temp.json')
useful_input = json.load(f2)
df=pd.read_json(useful_input)
print(df)
df.to_csv('results.csv')
回答by Akavall
You just need to pass the address string to pd.read_json()
:
您只需要将地址字符串传递给pd.read_json()
:
df=pd.read_json("temp.json")
回答by Martín Mu?oz del Río
You have not to use json module:
您不必使用 json 模块:
Try:
尝试:
import pandas as pd
df=pd.read_json("temp.json")
print(df)
df.to_csv('results.csv')
回答by KS HARSHA
import pandas as pd
df = pd.read_json('data.json')
df.to_csv('data.csv', index=False, columns=['title', 'subtitle', 'date', 'description'])
import pandas as pd
df = pd.read_csv("data.csv")
df = df[df.columns[:4]]
df.dropna(how='all')
df.to_json('data.json', orient='records')