105

I was just wondering if I can rename column names by their positions. I know how to rename them by their actual names using:

df.rename(columns = {})

How do I do it if I do not know the column names and know only their positions?

MrFun
  • 2,303
  • 1
  • 15
  • 16
JungleDiff
  • 3,221
  • 10
  • 33
  • 57

2 Answers2

232

try this

df.rename(columns={ df.columns[1]: "your value" }, inplace = True)
amonk
  • 1,769
  • 2
  • 18
  • 27
Exprator
  • 26,992
  • 6
  • 47
  • 59
  • 7
    For some reason, I needed `df=df.rename({})` after this for it to take effect – Shadi Sep 11 '17 at 12:03
  • 4
    I would go with John Zwinck's solution. This solution will actually lead to some strange bugs, as noted here: https://stackoverflow.com/questions/43291781/after-rename-column-get-keyerror – rnorris Sep 27 '17 at 22:31
  • I tried this solution and got really weird errors down the track in my code. I was hard to find the problem and it all came down to use this solution. So I confirm what @rnorris explained - TRY AND AVOID THIS AS IT MAY LEAD TO PROBLEMS. Try John Zwinck's solution instead, which doesn't cause problems. – jberrio Aug 27 '18 at 06:29
  • 1
    Use `df.rename(columns={ df.columns[1]: "your value"}, inplace=True)`. Otherwise a copy is returned. See the documentation: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename.html – Lorem Ipsum Jan 21 '19 at 20:55
  • 1
    is it possible to do this without having "df" in the rename statement ? – criticalth Apr 03 '19 at 14:22
  • 23
    This approach only works if all columns names are unique. However, if say, `df.columns[1] = df.columns[5]` then calling just `df.columns[1]` will change both `df.columns[1`] and `df.columns[5]`. – Will Bachrach Dec 16 '19 at 20:10
  • If you know exactly which specific column you wish to rename, probably just try something like `df.columns.values[1] = "some new column name"` – wywy_ds6699 Aug 30 '22 at 02:02
60

You can do this:

df.rename(columns={ df.columns[1]: "whatever" })
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • This didn't work with the following column name `International airline passengers: monthly totals in thousands. Jan 49 ? Dec 60` – Shadi Sep 11 '17 at 12:04
  • 18
    Note that as for the standard behavior there will be a copy created and returned. You can add `inplace=True` after the `}` to modifiy the object in place. – Ace7k3 Jan 25 '18 at 20:54
  • Not OP but thanks a lot for the answer. Could you tell me what does the keyword `inplace` do in this case please? I've been trying to figure it out as I could run the code when I set it to `True`. Thanks again. – Bowen Liu Dec 06 '18 at 20:20
  • @BowenLiu: Have you read the documentation? It describes `inplace`. – John Zwinck Dec 07 '18 at 06:16