您的列值似乎在实际 json 字符串之前有一个额外的数字。所以你可能想先把它去掉(跳到Method如果情况并非如此)
一种方法是将函数应用于列
# constructing the df
df = pd.DataFrame([['0 {"a":"1","b":"2","c":"3"}'],['1 {"a" :"4","b":"5","c":"6"}']], columns=['json'])
# print(df)
json
# 0 0 {"a":"1","b":"2","c":"3"}
# 1 1 {"a" :"4","b":"5","c":"6"}
# function to remove the number
import re
def split_num(val):
p = re.compile("({.*)")
return p.search(val).group(1)
# applying the function
df['json'] = df['json'].map(lambda x: split_num(x))
print(df)
# json
# 0 {"a":"1","b":"2","c":"3"}
# 1 {"a" :"4","b":"5","c":"6"}
Method:
一旦df
是上面的格式,下面将把每个行条目转换为字典:
df['json'] = df['json'].map(lambda x: dict(eval(x)))
然后,申请pd.Series
到专栏就可以了
d = df['json'].apply(pd.Series)
print(d)
# a b c
# 0 1 2 3
# 1 4 5 6