'How to change a range of column names in dataframe?

The column names of my dataframe looks like:

Country Code 1900.0 1901.0 1902.0 1903.0 1904.0......

Now I would like to change the numbers from float type to string, so I use:

df.columns[2:] = [str(int(x)) for x in df.columns[2:]]

but it shows error:

TypeError: Index does not support mutable operations

I know I can use dict to change column names, but what if there are too many names having to be changed?



Solution 1:[1]

You can create a dictionary from your list comprehension and use that to rename the columns:

df.rename(columns={x: str(int(x)) for x in df.columns[2:]}, inplace=True)

For example:

df = pd.DataFrame(columns=[1900.0,1901.0,1902.0,1903.0,1904.0,1906.0])
df.rename(columns={x: str(int(x)) for x in df.columns[2:]}, inplace=True)

Result:

>>> df
Empty DataFrame
Columns: [1900.0, 1901.0, 1902, 1903, 1904, 1906]
Index: []

Solution 2:[2]

When you call df.columns, it returns an Index type object, which you cannot use list comprehension on (hence the error). I would suggest making a variable cols which is the column names as a list, change the floats to strings in this list then re-assign to the columns as below:

df = pd.DataFrame(columns=['Country', 'Code', 1900.0, 1901.0, 1902.0, 1903.0, 1904.0])
cols = df.columns.to_list()
cols[2:] = [str(int(x)) for x in cols[2:]]
df.columns = cols

Output:

Empty DataFrame
Columns: [Country, Code, 1900, 1901, 1902, 1903, 1904]
Index: []

Solution 3:[3]

I'm not sure why you're getting that error. I'm also not sure what you were trying to do with the [2:] inside and outside your expression.

When you do the int(x) it deletes the decimals in the number. If you have a list of floats and want to convert them to string you can simply do:

list_of_strings_with_decimals = [str(x) for x in list_of_floats]

If you want to get rid of the decimals you can do it like this:

list_of_strings_without_decimals = [str(int(x)) for x in list_of_floats]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Derek O
Solution 2
Solution 3 rnavarro