Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rename pandas column of type datetime pandas

i have dataframe like this:

df=pd.DataFrame(data={'2021-11-21':['10','20'],'2021-11-14':['39','21']})

df
2021-11-21    2021-11-14
10            39
20            21

i want rename columns like this:

curr_week_2021-11-21    prev_week_2021-11-14
10                      39
20                      21

i tried this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df_cols=df.columns.to_list()
df=df.rename(columns={'2021-11-21':'curr_week_'+df_cols[0],'2021-11-14':'prev_week_'+df_cols[1]})

but it did not work.

>Solution :

If you want to use rename create a dict mapping:

df = df.rename(columns={c: f"{p}_{str(c)}"
                  for c, p in zip(df.columns, ['curr_week', 'prev_week'])})
print(df)

# Output:
  curr_week_2021-11-21 prev_week_2021-11-14
0                   10                   39
1                   20                   21
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading