How to select dataframe columns with lists and ranges combined

前端 未结 1 1899
自闭症患者
自闭症患者 2020-12-07 03:21

Please consider this df:

df = pd.DataFrame({\'a\':[1,2], \'b\':[1,2], \'c\':[1,2], \'d\':[1,2], \'e\':[1,2], \'f\':[1,2], \'g\':[1,2], \'h\':[1,2]})

   a  b         


        
相关标签:
1条回答
  • 2020-12-07 04:11

    You can do this:

    df.iloc[:, [0, 3] + list(range(5,8))]
    

    [0, 3] + list(range(5,8)) concatenates 2 lists, combining your explicit list with a list derived from your desired range.

    Alternatively, you can use numpy.r to build an indexing array for you:

    import numpy as np
    
    df.iloc[:, np.r_[0,3,5:8]]
    
    np.r_[0,3,5:8]  # array([0, 3, 5, 6, 7])
    

    This would be useful, for example, if you have multiple ranges.

    0 讨论(0)
提交回复
热议问题