python - 将 pandas 数据帧转换为 json 或字典,然后返回到具有非唯一列的 df

python - Convert pandas dataframe to json or dict and then back to df with non-unique columns

我需要将数据帧从后端发送到前端,因此首先需要将其转换为 JSON 可序列化的对象或直接转换为 JSON。问题是我有一些没有唯一列的数据框。我查看了 orient 参数、to_json()to_dict()from_dict() 方法,但仍然无法正常工作...

目标是能够将 df 转换为 json 可序列化的东西,然后返回到其初始状态。

我也很难使用 pd.read_clipboard 复制粘贴它,所以我包含了一个示例 df 作为图像导致问题(抱歉!)。

我找到了让它工作的方法。

这是一个简单的可重现示例:

import pandas as pd
import json

# create simple df with two identical named columns
df = pd.DataFrame([[1, 2, 3, 4]], columns=['col1', 'col2', 'col1', 'col2'])

# orient='split' conservers order
jsonized_df = df.to_json(orient='split')

# suppose the df is part of a bigger data structure being sent to another app
random_dict = {'foo': 'bar'}
all_data = [random_dict, jsonized_df]
data_to_frontend = json.dumps(jsonized_df)

# then from the other app
all_data = json.loads(data_to_frontend)
final_df = pd.read_json(all_data[1], orient='split') #important to remember to include the orient parameter when reading the json df as well!

final_df 将与 initial_df 相同,并保留顺序!