我想展平Pandas DataFrame中的JSON列 [英] I want to flatten JSON column in a Pandas DataFrame
本文介绍了我想展平Pandas DataFrame中的JSON列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个输入数据框df,如下所示:
I have an input dataframe df which is as follows:
id e
1 {"k1":"v1","k2":"v2"}
2 {"k1":"v3","k2":"v4"}
3 {"k1":"v5","k2":"v6"}
我想拉平"列"e",以便得到的数据框为:
I want to "flatten" the column 'e' so that my resultant dataframe is:
id e.k1 e.k2
1 v1 v2
2 v3 v4
3 v5 v6
我该怎么做?我尝试使用json_normalize,但没有成功
How can I do this? I tried using json_normalize but did not have much success
推荐答案
Here is a way to use pandas.io.json.json_normalize()
:
from pandas.io.json import json_normalize
df = df.join(json_normalize(df["e"].tolist()).add_prefix("e.")).drop(["e"], axis=1)
print(df)
# e.k1 e.k2
#0 v1 v2
#1 v3 v4
#2 v5 v6
但是,如果您的列实际上是str
而不是dict
,那么您首先必须使用json.loads()
映射它:
However, if you're column is actually a str
and not a dict
, then you'd first have to map it using json.loads()
:
import json
df = df.join(json_normalize(df['e'].map(json.loads).tolist()).add_prefix('e.'))\
.drop(['e'], axis=1)
这篇关于我想展平Pandas DataFrame中的JSON列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文