Viont
Viont

Reputation: 43

Python / Pandas: Renaming several column names in DataFrame based on condition/index

I'm quite new to Python and Pandas. Tried so far to find an answer on the forum, but wuthout success.

My problem is the following:

E.g.:

Col1 Col2 Wk 1- Wk 4 01.01.2021 01.02.2021 ...
1111 2222 .......... .......... .......... ...

I'd like to get the following:

Col1 Col2 Wk 1- Wk 4 25.01.2021 25.02.2021 ...
1111 2222 .......... .......... .......... ...

I tried to get it solved through adressing the column index range with df.columns, following the code:

df.columns[m3_idx:] = df.columns[m3_idx:].str.replace("^01", "25")

where m3_idx is the index of the column, where the renaming should start. But I get a TypeError:

Exception has occurred: TypeError
Index does not support mutable operations

How can I address the column indexes in order to specify the range of the columns, where the headers are to be changed?

EDIT: The idea is to change headers of only slice of the column range, as some of the "weekly data" columns before the monthly ones may start with the same string "01", which is not to be changed

Upvotes: 1

Views: 566

Answers (2)

Armali
Armali

Reputation: 19405

I need to rename first 2 characters of the column name string from 01 to (say) 25

You can use pandas.DataFrame.rename:

df = df.rename(lambda x: x[:2].replace("01", "25")+x[2:], axis="columns")    

(the x above is set to each name of the "columns" axis; the name is changed to the resulting value).

Here's a variant which replaces only names from the m3_idxth column on:

df.rename(columns = lambda x, idx=iter(range(df.columns.size)):
                        x if next(idx) < m3_idx else x[:2].replace("01", "25")+x[2:],
          inplace=True)

Upvotes: 0

Armali
Armali

Reputation: 19405

Exception has occurred: TypeError
Index does not support mutable operations

This error is due to the left hand side of the assignment df.columns[m3_idx:] = ... (the right hand side works) - we can't assign to the slice. So, to make this work, we can construct the whole column index and assign to df.columns:

df.columns = pd.Index.union(df.columns[:m3_idx],
                            df.columns[m3_idx:].str.replace("^01", "25", regex=True),
                            sort=False)

Upvotes: 1

Related Questions