将一列json字符串转换为数据列

时间:2018-06-02 11:32:33

标签: python json pandas dataframe

我有一个大约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

请帮忙

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

如果您在pandas中使用数据帧,则可以使用称为from_dict的库函数之一,该函数从字典创建数据帧。

如果你的数据是json,你可以使用json库很容易地将它转换为dict。

import json
import pandas 

my_dict = json.loads({"a" ;"4","b":"5","c":"6"})
pandas.DataFrame.from_dict(my_dict)

您可以将此逻辑应用于您的行。

答案 2 :(得分:0)

with open(json_file) as f:
    df = pd.DataFrame(json.loads(line) for line in f)