Pandas Mass Renaming Columns
I have a excel file which has a dates as column headers. The dates span to about 100 columns. I want to rename all these dates as Month1, Month2 and so forth. i am new to Pandas
Solution 1:
IIUC, we can create a dictionary using pd.to_datetime
to get the Month Number.
I've used a psuedo list but you'll need to amend the
format='%B_%Y')
to format='%b_%Y')
or whatever format your column name is.
setup
import pandas as pd
import numpy as np
import calendar
year_cols = ['colA','colB'] + [f"{c}_{i}"for i inrange(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 7columns
colA colB January_2020 February_2020 March_2020 April_2020 May_2020
0168296288298420172199
Create a dictionary.
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
rename columns.
df = df.rename(columns=rename_dict)
print(df.iloc[:,:7]) # print 7columns
colA colB Month01 Month02 Month03 Month04 Month05
016829628829842017219
Post a Comment for "Pandas Mass Renaming Columns"