首页 > 解决方案 > 更改数据框中的列名称并将其融化

问题描述

我有一个代码可以使用 Python 将几个 excel 合并在一起,但我无法使用 df.rename() 重命名该数据框中的任何内容。有人可以解释为什么吗?谢谢!

import os
import xlrd
import pandas as pd


def file_name(file_dir):
    list=[]
    for file in os.listdir(file_dir):
        if os.path.splitext(file)[1] == '.xlsx':
            list.append(file)
    return list

path = r'E:\Sync\External\Test'
wks = file_name(path)
data = []   
for i in range(len(wks)):
    read_xlsx = xlrd.open_workbook(path + '\\' + wks[i])
    sheet1 = read_xlsx.sheets()[1] 
    nrow =  sheet1.nrows
    title = sheet1.row_values(0)   
    location = os.path.splitext(wks[i])[0]

    for j in range(6,nrow): 

        a = sheet1.row_values(j)
        a.insert(0,location)
        print(a)
        data.append(a)

content= pd.DataFrame(data)

content.rename({'0': 'X', '1': 'Y'}, axis=1, inplace=True)


#content.to_csv(path+'\\test.xlsx', sep=',', header=True, index=False)

content.to_excel(path+'\\test.xlsx', header=True, index=False)

代码如上,没有错误显示,但它只是不起作用(重命名部分)

标签: pythonexcelpandaslistdataframe

解决方案


推荐阅读