我有一个大约30000行的大数据框和一个包含json字符串的单列。每个json字符串包含多个变量及其值,我想将此json字符串分解为数据列

两行看起来像

0 {"a":"1","b":"2","c":"3"}
1 {"a" ;"4","b":"5","c":"6"}


我想将其转换为像

a   b   c
1   2   3
4   5   6


请帮忙

最佳答案

您的列值似乎在实际的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

10-06 10:58