如上所示,csv文件中包含以中括号{}包含的json字段,可用如下方法提取:
import pandas as pd
from datetime import date
today=str(date.today())
import jsonfilepath='/Users/kangyongqing/Documents/kangyq/202401/调课功能使用统计/'
file1='04老师调课明细数据.csv'df1=pd.read_csv(filepath+file1,dtype='object')
print(df1.head(1).T)# json.load():是从文件中加载内容并转换成json;
# json.loads():是将字符串转换成json。tmp1=pd.json_normalize(df1['operatereason'].apply(json.loads).tolist())
tmp2=pd.json_normalize(df1['info'].apply(json.loads).tolist())
print(tmp1)
df2=pd.concat((df1,tmp1,tmp2),axis=1)
print(df2.head(1).T)df3=pd.concat((df1.drop(columns=['operatereason','info']),tmp1,tmp2),axis=1)
print(df3.columns)
#删除原数据列
划重点:
tmp1=pd.json_normalize(df1['operatereason'].apply(json.loads).tolist())
df2=pd.concat((df1,tmp1,tmp2),axis=1)
即可提取出特定列包含的子字段数据;
结果如下: