Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming Pandas DataFrame columns that are numbers

Tags:

python

pandas

I have a DataFrame that has integers for column names that looks like this:

      1     2     3     4
 Red  7     3     2     9
 Blue 3     1     6     4

I'd like to rename the columns. I tried using the following

df = df.rename(columns={'1': 'One', '2': 'Two', '3': 'Three', '4': 'Four'})

However that doesn't change the column names. Do I need to do something else to change column names when they are numbers?

like image 803
nostradukemas Avatar asked Apr 16 '19 17:04

nostradukemas


People also ask

How do I rename a specific column in Pandas?

Pandas Rename Single Column If you want to rename a single column, just pass the single key-value pair in the columns dict parameter. The result will be the same if there is a non-matching mapping in the columns dictionary.

How do I rename a column in Pandas based on index?

You can rename pandas DataFrame column name by index (position) using rename() method or by assigning column name to df. columns. values[index] .

How do I rename a column in a DataFrame list?

Rename Columns with List using set_axis() Alternatively, you can use DataFrame. set_axis() method to rename columns with list. use inplace=True param to rename columns on the existing DataFrame object.


3 Answers

You need to remove the quotes:

df = df.rename(columns={1: 'One', 2: 'Two', 3: 'Three', 4: 'Four'})
like image 61
bzu Avatar answered Oct 23 '22 05:10

bzu


What if you use the following:

>>> df.columns = ['One', 'Two', 'Three', 'Four']
>>> df
    One Two Three   Four
0   7   3   6       9
1   3   1   2       4
like image 25
lmiguelvargasf Avatar answered Oct 23 '22 05:10

lmiguelvargasf


You can use two way to change columns name in Pandas DataFrame.

  1. Changing the column name using df.columns attribute.

    df.columns = ['One', 'Two', 'Three', 'Four']

  2. Using rename() function

    df = df.rename(columns={1: 'One', 2: 'Two', 3: 'Three', 4: 'Four'})

like image 32
sameera lakshitha Avatar answered Oct 23 '22 03:10

sameera lakshitha