简体   繁体   English

如何修改 Pandas 的有序字典的键?

[英]How to modify the Key of an Ordered Dictionary at Pandas?

I am reading an excel file with around 2000 sheets with pandas.我正在阅读一个 excel 文件,其中包含大约 2000 张带有 pandas 的文件。 The excel sheet is loaded as an Ordered Dictionary since I have used the following: excel 工作表作为有序字典加载,因为我使用了以下内容:

test = pd.read_excel('test.xlsx', sheet_name=None)

Let's assume that it looks like that:让我们假设它看起来像这样: 来自excel文件的有序字典

I would like to modify the name of the sheets and save the Ordered Dictionary to an excel file again.我想修改工作表的名称并将有序字典再次保存到 excel 文件中。 The names of the sheets are stored as the keys of the Ordered Dictionary, so basically I would like to just modify the keys and save to excel again.工作表的名称存储为有序字典的键,所以基本上我只想修改键并再次保存到 excel。

As it can be noticed the name of the key ends with a year, ie 2020, 2022 etc. I would like all the keys to be modified such that they are reduced by 1, so the name of the keys are now 2019, 2021 etc. I would also like to make sure that the content does not change;可以注意到键的名称以年份结尾,即 2020、2022 等。我希望修改所有键,使它们减 1,所以键的名称现在是 2019、2021 等.我还想确保内容不会改变; meaning that the dataframe that used to assigned to A.AA.XX2020 is now assigned to A.AA.XX2019.这意味着以前分配给 A.AA.XX2020 的 dataframe 现在分配给 A.AA.XX2019。 The "General" sheets does not have to be modified.不必修改“常规”表。

Since there are many sheets in the excel file, I would prefer an automated procedure.由于 excel 文件中有很多工作表,我更喜欢自动化程序。

I hope following will suit your needs:我希望以下内容能满足您的需求:

import pandas as pd

# read Excel file
test = pd.read_excel('test.xlsx', sheet_name=None)

# get keys from dict without 'General'
keys = list(test.keys())
keys.remove('General')

# iterate over keys
for key in keys:

    # get the old year
    year_old = int(key[-4:])

    # make the new year
    year_new = year_old - 1

    # create name for new key
    key_new = key[:-4] + str(year_new)

    # copy values from old key in new key and delete old key
    test[key_new] = test.pop(key)

# write dataframes from dict in one Excel file with new sheet names    
with pd.ExcelWriter('test_new.xlsx') as writer:
    for sheet_name, df in test.items():
        df.to_excel(writer, sheet_name=sheet_name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM