DataFram与Json转换

DataFrame与Json转换

    • DataFrame转Json
    • 将Json转为DataFrame
    • str,unicode格式的list转list

DataFrame转Json

import pandas as pd

df = pd.read_csv("./PoliceKillingsUS.csv").ix[0:10,2:-1]
df_to_json = df.to_json(orient="records")

df:
DataFram与Json转换_第1张图片

df_to_json:
在这里插入图片描述

将Json转为DataFrame

import pandas as pd
import json
from pandas.io.json import json_normalize

str_to_list = json.loads(df_to_json)

#方式一
df0 = pd.DataFrame(str_to_list)

#方式二
df1 = json_normalize(str_to_list)

df0:
DataFram与Json转换_第2张图片

df1:
DataFram与Json转换_第3张图片

str,unicode格式的list转list

#coding:utf-8
import pandas as pd
import json
import ast
from pandas.io.json import json_normalize


df = pd.read_csv("./PoliceKillingsUS.csv").ix[0:10,2:-1]
df_to_json = json.dumps(df.to_json(orient="records").replace(':true',":True").replace('false',"False"))
#type of json_to_str is str
json_to_str = json.loads(df_to_json).encode('utf-8')
#type of json_to_list is list
json_to_list = ast.literal_eval(json_to_str)

#coding:utf-8
import pandas as pd
import json
import ast
from pandas.io.json import json_normalize


df = pd.read_csv("./PoliceKillingsUS.csv").ix[0:10,2:-1]
df_to_json = json.dumps(df.to_json(orient="records").replace(':true',":True").replace('false',"False"))
#type of json_to_str is unicode
json_to_str = json.loads(df_to_json)
#type of json_to_list is list
json_to_list = ast.literal_eval(json_to_str)

你可能感兴趣的:(python)