17

I have a dataframe whose columns are RangeIndex. I want to change the names.

import pandas as pd
>>> my_df

            0         1
Alpha    -0.1234     0.001
Beta     0.7890      0.005

>>> my_df.columns
RangeIndex(start=0, stop=2, step=1)

I want to do something like:

 my_df = my_df.rename({'0': 'Betas', '1': 'P-values})

And it should look like:

>>> my_df

            Betas         P-values
Alpha    -0.1234     0.001
Beta     0.7890      0.005

But it does not change the column names.

9
  • 1
    Use my_df.rename(columns={0: 'Betas', 1: 'P-values'})
    – Zero
    Sep 14, 2018 at 14:10
  • 1
    you can just assign directly my_df.columns = ['Betas', 'P-values']
    – EdChum
    Sep 14, 2018 at 14:12
  • @EdChum Thank you. That also works. Which method is more efficient? Sep 14, 2018 at 14:14
  • @Wen To which problem is this possibly a duplicate? Sep 14, 2018 at 14:22
  • @JunSeongJang stackoverflow.com/a/11354850/7964527
    – BENY
    Sep 14, 2018 at 14:23

1 Answer 1

8

Simple and straightforward.

my_df.rename(columns = { '0': 'Betas', '1': 'P-values' }, inplace=True)

Even nicer as borrowed from Edchum

my_df.columns = ['Betas', 'P-values']

Not the answer you're looking for? Browse other questions tagged or ask your own question.