Index pandas DataFrame by column numbers, when column names are integers

前端 未结 3 2152
遥遥无期
遥遥无期 2021-02-20 00:14

I am trying to keep just certain columns of a DataFrame, and it works fine when column names are strings:

In [2]: import numpy as np

In [3]: import pandas as pd         


        
3条回答
  •  长发绾君心
    2021-02-20 00:40

    This is certainly one of those things that feels like a bug but is really a design decision (I think).

    A few work around options:

    rename the columns with their positions as their name:

     df.columns = arange(0,len(df.columns))
    

    Another way is to get names from df.columns:

    print df[ df.columns[[1,3]] ]
       11  13
    x   1   3
    y   8  10
    u  15  17
    z  22  24
    w  29  31
    

    I suspect this is the most appealing as it just requires adding a wee bit of code and not changing any column names.

提交回复
热议问题