您的列值似乎在实际的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"}
方法:
一旦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
本文介绍了一种从带有数字前缀的JSON字符串中去除这些数字的方法,并将其转换为Python字典,最终利用Pandas将字典转换为表格形式。
2133

被折叠的 条评论
为什么被折叠?



