在本文中,我们将探讨如何使用python中的pandas库将dataframe(以下简称df)数据转换为特定的格式,以便在前端的datatables中渲染。今天的重点是如何将df按行和按列进行转换。
目标
在网站开发过程中,经常需要将后端的Df数据转换成前端Datatables可识别的格式。这种格式通常是一个列表,其中每个元素是一个字典,字典的键对应前端表格的列名,值则对应表格的单元格值。以下是一个示例Df及其转换后的格式:

转换后的列表格式如下:
立即学习“Python免费学习笔记(深入)”;

代码
以下是实现上述转换的Python代码:
import pandas as pd
dict_1 = {"time": ["2019-11-02", "2019-11-03", "2019-11-04", "2019-11-05",
"2019-12-02", "2019-12-03", "2019-12-04", "2019-12-05"],
"pos": ["A", "A", "B", "B", "C", "C", "C", "D"],
"value1": [10, 20, 30, 40, 50, 60, 70, 80]}
df_1 = pd.DataFrame(dict_1, columns=["time", "pos", "value1"])
print("原数据", "\n", df_1, "\n")
print("\n按行输出")
list_fields = df_1.to_dict(orient='records')
print(list_fields)代码截图:

部分代码解读
list_fields = df_1.to_dict(orient='records')
to_dict
orient='records'
records
延伸
除了按行转换,pandas也支持按列转换。通过查阅
orient
list
dict_fields = df_1.to_dict(orient='list') print(dict_fields)
按列转换的代码截图:

按列转换的结果:

以上就是Python-科学计算-pandas-14-df按行按列进行转换的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号