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

4
  • But you still want 10 column names 0-9 ... 90-99? Commented Oct 6, 2019 at 16:50
  • 1
    Possible duplicate of Renaming columns in pandas Commented Oct 6, 2019 at 17:03
  • yes 0-9 to 90-99 @myradio Commented Oct 10, 2019 at 15:53
  • See my answer, is that what you want? Commented Oct 10, 2019 at 22:35

3 Answers 3

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')
Sign up to request clarification or add additional context in comments.

1 Comment

@Dodo3 if it works, then consider accepting the answer. Thanks! :)
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"})

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.