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.

Jun Seong Jang
  • 385
  • 2
  • 4
  • 12
  • 1
    Use `my_df.rename(columns={0: 'Betas', 1: 'P-values'})` – Zero Sep 14 '18 at 14:10
  • 1
    you can just assign directly `my_df.columns = ['Betas', 'P-values']` – EdChum Sep 14 '18 at 14:12
  • @EdChum Thank you. That also works. Which method is more efficient? – Jun Seong Jang Sep 14 '18 at 14:14
  • @Wen To which problem is this possibly a duplicate? – Jun Seong Jang Sep 14 '18 at 14:22
  • @JunSeongJang https://stackoverflow.com/a/11354850/7964527 – BENY Sep 14 '18 at 14:23
  • @Wen It's not really the same problem because I am trying to rename RangeIndex, not strings. It's a SIMILAR problem, but definitely not SAME or DUPLICATE. – Jun Seong Jang Sep 14 '18 at 14:24
  • @JunSeongJang, Direct assignment to columns looks more elegant. – Karn Kumar Sep 14 '18 at 14:25
  • @JunSeongJang all the function behind your problem and the tag question are same . rangeindex still can be rename using `rename` ., If you like i will open it. – BENY Sep 14 '18 at 14:29
  • direct naming doesn't work for me. My df is one row created from a list, then transposed. When I try direct naming, e.g. `my_df.columns = ['Betas', 'P-values']` it results in `AttributeError: 'Series' object has no attribute 'columns' ` (yet `type(my_df)` is ``) – James Dec 22 '19 at 22:28

1 Answers1

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']
Karn Kumar
  • 8,518
  • 3
  • 27
  • 53