Dodo3
Dodo3

Reputation: 43

Renaming columns in a dataframe - Python

Hi I have the following dataframe and I would like to change the name of column.

    0   1   2   3   4   5   6   7   8   9
Hollande    35  29  68  88  82  74  47  26  12  4
Rues-Basses-Fusterie    0   0   8   7   5   4   8   1   0   0 

Instead of having 0 1 2 , I would like to get a range like that:

    0-9  10-19  20-29
Hollande    35  29  68  88  82  74  47  26  12  4
Rues-Basses-Fusterie    0   0   8   7   5   4   8   1   0   0 

Thanks for helping me :)

Upvotes: 0

Views: 110

Answers (3)

natka_m
natka_m

Reputation: 1632

If you want to rename all the columns in the df dataframe, as @RamWill pointed out, it's best to use the rename method, with an anonymous function:

df.rename(columns=lambda x: f"{int(x) * 10}-{int(x) * 10 + 9}")

You can also add the inplace=True argument, which means that the original data frame is modified, and no copy is created.

The new columns:

> df.columns                                                                                
Index(['0-9', '10-19', '20-29', '30-39', '40-49', ...], dtype='object')

Upvotes: 1

myradio
myradio

Reputation: 1785

If you want all the columns renamed in the way you showed only or the first three (but you don't want to change the number of columns) you can do something like this assuming your data frame is called yourDataFrame,

data_top = yourDataFrame.columns
newcols = []
for a in data_top.astype(int):
    newcols.append(str(a*10) + '-' + str(a*10+9))
yourDataFrame.columns = newcols

Using this piece of code you can rename the columns in that way for many pandas dataframes independently of the number of columns that they have.

Upvotes: 0

RamWill
RamWill

Reputation: 318

This is explained in the documentation. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename.html

In your example you could do

df.rename(columns={"0": "0-9", "1": "10-19" ... , "9": "90-99"})

Upvotes: 1

Related Questions