熊猫批量重命名列

问题描述 投票:0回答:1

我有一个Excel文件,其中以日期作为列标题。日期跨越约100列。我想将所有这些日期重命名为Month1,Month2,依此类推。我是Pandas和Python的新手。

我发现的一种方法是创建一个新列名列表,然后用新列名替换旧列名,但是,这意味着我必须输入100多个列。

是否有一种条件,例如从第7列开始,将所有列标题重命名为Month1 +1?

Example

截至上述每个月,我要到2028年才能使用,因此需要将其全部重命名。即从month1到12月,然后从4月month1-12重新开始

我有类似的东西;

 df_cols = ['Project Name', 'Project Principal', 'Value', 'value as per Vision', 'Proability', 
'Account', 'Phase', 'Number', 'ProjectType', 'Rolling 12mnths', 'Month0', 'Month1', 'Month2', 
'Month3', 'Month4', 'Month5', 'Month6', 'Month7', 'Month8', 'Month9', 'Month10', 'Month11', 
'Month12', 'Total']
 df.columns = df_cols
python-3.x pandas numpy
1个回答
0
投票

[IIUC,我们可以使用pd.to_datetime创建字典以获取月份编号。

我使用了伪列表,但您需要修改

[format='%B_%Y')format='%b_%Y')

或您的列名使用的任何格式。

设置

import pandas as pd
import numpy as np
import calendar

year_cols = ['colA','colB'] + [f"{c}_{i}" for i in range(2020,2028) for c in calendar.month_name[1:]] 

nums = np.random.randint(0,500,size=len(year_cols))

df = pd.DataFrame([nums],columns=year_cols)

print(df.iloc[:,:7]) # print 7 columns

   colA  colB  January_2020  February_2020  March_2020  April_2020  May_2020
0   168   296           288            298         420         172       199

创建字典。

rename_dict = {i : f"Month{pd.to_datetime(i,format='%B_%Y').strftime('%m')}" 
               for i in df.iloc[:,2:].columns}

for k,v in rename_dict.items():
    if v == 'Month01':
        print(f'{k} -- > {v}')

January_2020 -- > Month01
January_2021 -- > Month01
January_2022 -- > Month01
January_2023 -- > Month01
January_2024 -- > Month01
January_2025 -- > Month01
January_2026 -- > Month01
January_2027 -- > Month01

重命名列。

df = df.rename(columns=rename_dict)

print(df.iloc[:,:7]) # print 7 columns




   colA  colB  Month01  Month02  Month03  Month04  Month05
0   168   296      288      298      420      172      19
© www.soinside.com 2019 - 2024. All rights reserved.