如何按特定顺序放置 pandas 数据框 header 名称?

How to place pandas data frame header names in a specific order?

所以我尝试导入一些 excel 并创建所有数据的列表,这是我的代码:

import os
import pandas as pd
cwd = os.path.abspath('') 
files = os.listdir(cwd)  
df = pd.DataFrame()
for file in files:
    if file.endswith('.XLSX'):
        df = df.append(pd.read_excel(file), ignore_index=True)

df = df.where(df.notnull(), None)
array = df.values.tolist()
print(array)

另一方面,excel 看起来像这样:

    product cost   used_by prime
    name    price  gender  yes or no
    name    price  gender  yes or no
    ... and so on 

然而,并不是所有的人都有product cost used_by prime的奇数(第一种情况)。其中一些,例如,格式为cost product prime used_by(case two order)。当然,pandas 能够 auto-sort 他们并确保数据找到正确的 header,但我 运行 遇到了问题。

所以基本上,我 运行 这段代码在两个不同的设备上使用相同的数据和代码,但结果不同。其中一个是 case one order,而另一个是 case two order。我想要一行代码来确保数据框始终按 product cost used_by prime 的顺序排列,但我不确定如何。

你能告诉我它的 python 代码吗?提前谢谢你。

您可以尝试在加载 csv 文件后立即重新排序

df = df[['product', 'used_by', 'prime']]