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

标签 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

请帮忙

最佳答案

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

关于python - 将一列json字符串转换成列数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50656469/

相关文章:

python - sort_values 和 sort_index 有什么区别?

python - While 语句(在 shell 中没有结果)

python - 将 UTC 时间戳转换为日期时间对象,将夏令时考虑在内

java - 如何防止 gson 将整数转换为 double

python - Pandas 分组但保留另一列

python - Python 有什么方法可以从字符串列中提取最后 2 个字符并将其转换为数字列吗?

python - 使用多字节 key 对文件进行 XORing

python - 从 Pandas 到字典,第一列中的值将是键,第二列中的相应值将全部在列表中

java - 连接请求响应处理

python - json.dump() 给我 "TypeError: keys must be a string"