Pandas如何对带有Multi-column(多列名称)的数据排序并写入Excel中

来自:网络
时间:2024-03-18
阅读:
免费资源网 - https://freexyz.cn/

Pandas对带有Multi-column数据排序并写入Excel中

使用如下方式写入数据

import pandas as pd
import numpy as np

df = pd.DataFrame(np.array([[10, 2, 0], [6, 1, 3], [8, 10, 7], [1, 3, 7]]), columns=[['Number', 'Name', 'Name', ], ['col 1', 'col 2', 'col 3', ]])
df.to_excel('test.xlsx')

写入后的数据顺序是杂乱无章的。

Pandas如何对带有Multi-column(多列名称)的数据排序并写入Excel中

想要读取上述数据并让它们按Number列进行排序怎么办

可以采用如下方法。

import pandas as pd
import numpy as np

df = pd.DataFrame(np.array([[10, 2, 0], [6, 1, 3], [8, 10, 7], [1, 3, 7]]), columns=[['Number', 'Name', 'Name', ], ['col 1', 'col 2', 'col 3', ]])
df = df.sort_values([('Number', 'col 1')])
df.to_excel('test.xlsx')

最终的结果为:

Pandas如何对带有Multi-column(多列名称)的数据排序并写入Excel中

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

免费资源网 - https://freexyz.cn/
返回顶部
顶部