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:
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.
CodePudding user response:
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
CodePudding user response:
One way to do it programmatically with an arbitrary list of prefixes would be to use map
/zip
/join
:
prefixes = ['curr_week', 'prev_week']
df.columns = map('_'.join, zip(prefixes, df.columns))
output:
curr_week_2021-11-21 prev_week_2021-11-14
0 10 39
1 20 21