Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

python - Looking for an ideas to implement dynamic column renaming in pandas

I have 143 column names in my df and 141 columns has same column format as shown below and want to update last 3 bytes of column name with month for columns starting with passengers or want to update whole column like '2009-jan' format based on targeted value

0: 'airport', 1: 'type of traffic', 2: 'Passengers 2009M01', 3: 'Passengers 2009M02', 4: 'Passengers 2009M03', 5: 'Passengers 2009M04', 6: 'Passengers 2009M05', 7: 'Passengers 2009M06', 8: 'Passengers 2009M07', 9: 'Passengers 2009M08', 10: 'Passengers 2009M09', 11: 'Passengers 2009M10',

question from:https://stackoverflow.com/questions/65907190/looking-for-an-ideas-to-implement-dynamic-column-renaming-in-pandas

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
import calendar
# df = your dataframe
df = pd.DataFrame([[1,2],[2,4],[3,5]], columns=['Passengers 2009M01', 'Passengers 2009M02'])

column_names = df.columns.to_list()
for each_column in column_names:
    if('Passengers' in each_column):
        dd = each_column.split(' ')[-1]
        year, month= dd.split('M')
        month = calendar.month_name[int(month)].lower()[:3]
        df.rename(columns={each_column: f'{year}-{month}'}, inplace=True)

output

   2009-jan   2009-feb
0   1         2
1   2         4
2   3         5

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...