Home > Software design >  Can I use index position and also index slice in iloc function at the same time?
Can I use index position and also index slice in iloc function at the same time?

Time:01-10

Can I use: iloc[:, [1,2,3,27, 4:27]

I want to reorder column by column index and include all column in output

CodePudding user response:

Yes, you can, but you'll need to build a list of indices without the slice. Numpy has a nifty helper for this: np.r_:

>>> np.r_[1, 2, 3, 27, 4:27]
array([ 1,  2,  3, 27,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23, 24, 25, 26])

so your code becomes:

df.iloc[:, np.r_[1, 2, 3, 27, 4:27]]

CodePudding user response:

Yes, you can.. Use the following syntax to select and reorder the columns of a Pandas DataFrame:

df = df.iloc[:, [1, 2, 3, 27, 4:27]]

This will select the second, third, fourth, and twenty-eighth columns, as well as the fifth through twenty-seventh columns, and reorder them to be the first through twenty-eighth columns in the resulting DataFrame.

Note that the iloc indexer is used to select rows and columns based on their integer indices. In this case, the ':' is used to select all rows, and the list of integers '[1, 2, 3, 27, 4:27]' is used to select and reorder the columns. The '4:27' slice is used to select the fifth through twenty-seventh columns.

  • Related