【问题标题】:Iterately read sheets from excel file and modify column names in Python从 excel 文件中迭代读取工作表并在 Python 中修改列名
【发布时间】:2021-02-07 22:21:15
【问题描述】:

假设我有一个 excel 文件 data.xlsx,其中包含多个工作表:sheet1, sheet2, sheet3, etc.

import pandas as pd

xls = pd.ExcelFile('data.xlsx')
for sheet in xls.sheet_names:
    df = pd.read_excel('data.xlsx', sheet_name=sheet)

对于每个工作表,它具有相同的列名:'ISIN', 'Coupon', 'Issue Date', 'Maturity Date'

现在我需要迭代读取所有工作表并用date_list的元素修改列名ISIN,即date_list = ['2021-01', '2021-02', '2021-03', ...],然后保存为excel文件。

最终文件的sheet1 的列名将是['2021-01', 'Coupon', 'Issue Date', 'Maturity Date']sheet2 的将是['2021-02', 'Coupon', 'Issue Date', 'Maturity Date'],等等。

我如何在 Python 中做到这一点?谢谢。

【问题讨论】:

    标签: python-3.x pandas dataframe xlsxwriter


    【解决方案1】:

    rename 重命名数据框的列名并再次保存文件。

    import pandas as pd
    xlsx = pd.ExcelFile('data.xlsx')
    
    writer = pd.ExcelWriter('data_new.xlsx')
    
    for i, sheet_name in enumerate(xlsx.sheet_names):
        df = xlsx.parse(sheet_name)
    
        # renmae ISIN to '2021-01'...
        df.rename(columns={'ISIN': date_list[i]}, inplace=True)
        df.to_excel(writer, sheet_name=sheet) 
    
    writer.save()     
    

    【讨论】:

    • 它引发了SyntaxError: can't assign to function call,用于with writer as pd.ExcelWriter('data_new.xlsx'):
    • 好的,我将使用writer.save() 而不是with
    • 我的错,with pd.ExcelWriter('data_new.xlsx') as writer: 会起作用
    • NameError: name 'sheet_name' is not defined,你忘了定义sheet_name吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多