python - 如何在 Python 中展平其中一列包含 json 对象的数据框?

标签 python json python-3.x pandas dataframe

我有一个数据框,其中一列是一个 json 对象,如下所示

customer_id |    date    |             json_object
--------------------------------------------------------------------------
A101        | 2022-06-21 | {'name':['james'],'age':[55], 'hobby':['pubg']}
A102        | 2022-06-22 | {'name':['tarzan'],'status':[]}

jason对象内容不统一。在上面的示例中,第一行中的 json 对象为“爱好”,第二行的 json 对象中不存在。与第二行类似,属性状态为空,即 []

问题:如何在 Python 中展平这个数据框以创建一个新的数据框,其中每一行仅对应一个 json 对象,如下所示

customer_id |    date    | attribute
---------------------------------------------
A101        | 2022-06-21 | 'name': 'james'
A101        | 2022-06-21 | 'age': 55
A101        | 2022-06-21 | 'hobby': 'pubg'
A102        | 2022-06-22 | 'name': 'tarzan'
A102        | 2022-06-22 | 'status':

最佳答案

假设 json_object 的每个值都是一个 dict,您还可以使用以下方法:

df = pd.DataFrame(
    data = {
        "customer_id": ["A101", "A102"],
        "date": ["2022-06-21", "2022-06-22"],
        "json_object": [{'name': 'james','age':55, 'hobby':'pubg'}, {'name': 'tarzan','status':'single'}]
    }
)
df["json_object"] = df["json_object"].map(lambda x: [[i, x[i]] for i in x])
df = df.explode(column="json_object")
df.json_object = df.json_object.str[0].astype(str) + ": " + df.json_object.str[1].astype(str) 
df

------------------------------------------
    customer_id  date        json_object
0   A101         2022-06-21  name: james
0   A101         2022-06-21  age: 55
0   A101         2022-06-21  hobby: pubg
1   A102         2022-06-22  name: tarzan
1   A102         2022-06-22  status: single
------------------------------------------

编辑

自从您将数据框更改为

df = pd.DataFrame(
    data = {
        "customer_id": ["A101", "A102"],
        "date": ["2022-06-21", "2022-06-22"],
        "json_object": [{'name': ['james'],'age':[55], 'hobby':['pubg']}, {'name': ['tarzan'],'status':['single']}]
    }
)

我的代码必须作如下调整:

df = pd.DataFrame(
    data = {
        "customer_id": ["A101", "A102"],
        "date": ["2022-06-21", "2022-06-22"],
        "json_object": [{'name': ['james'],'age':[55], 'hobby':['pubg']}, {'name': ['tarzan'],'status':['single']}]
    }
)
df["json_object"] = df["json_object"].map(lambda x: [[i, x[i][0]] for i in x])
df = df.explode(column="json_object")
df.json_object = df.json_object.str[0].astype(str) + ": " + df.json_object.str[1].astype(str) 
df

如果包含空列表,则只需在 lambda 函数中添加一个 if-else 条件。请注意,我还重命名了下一个代码提取中的列。

df = pd.DataFrame(
    data = {
        "customer_id": ["A101", "A102"],
        "date": ["2022-06-21", "2022-06-22"],
        "json_object": [{'name': ['james'],'age':[55], 'hobby':['pubg']}, {'name': ['tarzan'],'status':[]}]
    }
)
df["json_object"] = df["json_object"].map(lambda x: [[i, x[i][0]] if x[i] else [i, ""] for i in x])
df = df.rename(columns={"json_object": "attribute"}).explode(column="attribute")
df.attribute = df.attribute.str[0].astype(str) + ": " + df.attribute.str[1].astype(str) 

关于python - 如何在 Python 中展平其中一列包含 json 对象的数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72713108/

相关文章:

python - 如何找出所需的窗口大小?

python - PCA fit() 运行时警告(在 true_divide 中遇到无效值)

javascript - 对 json 数据进行分类并将其存储在单独的数组中

python - 如何查看 Python 变量中存储的数据结构?

python - 如何在 Python 中将字符串转换为日期

php - 使用 App Engine Python 应用程序作为 PHP 应用程序的代理

python - 使用新键将 Pandas DataFrame 转换为 Dict 格式

javascript - 如何使用json数据计算Angular中的平均值

ios - 如何通过后台下载更新 iOS 应用程序的内容?

Python 的 print 语句后跟 sleep(...) 函数给出了意外的输出