[英]Python Pandas convert 1 column of combination of strings to multiple columns of categorical data
[英]Convert a column of json strings into columns of data
我有一个大约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
with open(json_file) as f:
df = pd.DataFrame(json.loads(line) for line in f)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.