Skip to main content
 首页 » 编程设计

python之将一列json字符串转换成列数据

2024年09月07日32freeliver54

我有一个大约 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 字符串之前有一个额外的数字。所以你可能想先把它去掉(如果不是这种情况,跳到方法)

一种方法是对列应用一个函数

# 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