[英]Transform python response to Json response
我已經研究了 python 代碼,該代碼自動讀取多個擴展名的數據幀並打印 DF 的前 100 行及其列的類型,並有可能在同一個簡單的 function 中添加更多內容,我目前正在研究以 JSON 格式做出響應但仍然無法這樣做,因為這是我第一次使用 Json API 因為我更喜歡數據分析/科學而不是編程感謝您的幫助和建議
import os
import modin.pandas as pd
def sqlread(con_w_sql, sep='#'):
con, sql = special_path.split(sep)
df = pd.read_sql(sql, con)
return df.head()
readict = {
".csv": {
"read": pd.read_csv
},
".tsv": {
"read": pd.read_csv
},
".json": {
"read": pd.read_json
},
".xlsx": {
"read": pd.read_excel
},
".xml": {
"read": pd.read_xml
},
".xls": {
"read": pd.read_excel
},
".hdf": {
"read": pd.read_hdf
},
".sql": {
"read": sqlread
}
}
def read_any(file):
_, ext = os.path.splitext(file)
df = readict[ext]["read"](file)
return df.head(100), df.dtypes
file = input("enter the path to the file you want to open : ")
read_any(file)
我嘗試了以下方法,將頭部和類型放入字典中,然后在字典上使用 json.dumps() 將其轉換為 JSON object 但它給了我一個錯誤:
import os
import modin.pandas as pd
import json
from distributed import Client
def sqlread(con_w_sql, sep='#'):
con, sql = special_path.split(sep)
df = pd.read_sql(sql, con)
return df.head()
readict = {
".csv": {
"read": pd.read_csv
},
".tsv": {
"read": pd.read_csv
},
".json": {
"read": pd.read_json
},
".xlsx": {
"read": pd.read_excel
},
".xml": {
"read": pd.read_xml
},
".xls": {
"read": pd.read_excel
},
".hdf": {
"read": pd.read_hdf
},
".sql": {
"read": sqlread
}
}
def read_any(file):
_, ext = os.path.splitext(file)
df = readict[ext]["read"](file)
head = df.head(100)
dtype = df.dtypes
jsonresp = {
"head": head,
"dtype": dtype
}
return json.dumps(jsonresp)
file = input("enter the path to the file you want to open : ")
read_any(file)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.