0

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 :)

Chandella07
  • 2,089
  • 14
  • 22
Dodo3
  • 43
  • 7

3 Answers3

1

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"})
RamWill
  • 288
  • 1
  • 3
  • 6
1

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')
natka_m
  • 1,297
  • 17
  • 22
0

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.

myradio
  • 1,703
  • 1
  • 15
  • 25