Using slice AND list of integers in pandas iloc?

Viewed 852

65 columns in the dataset. I'd like to select the first handful, then a couple further off. Can this be done in one operation? Or is it suggested to do in two and merge the two dfs?

Checked pandas iloc documentation and various StackOverflow questions.. nothing specific enough for me.

data.iloc[:,[0:27,57,63,64]]

Example of multi-step --

left = data.iloc[:,0:27]
right = data.iloc[:,[2,57,63,64]]
..merge on col 2
2 Answers

You need np.r_

df = data.iloc[:, np.r_[0:27,57,63,64]]

Per the docs for iloc, it can take a list or a slice. But what you could do instead is create a list for the slice you want and then use the unpacking operator to expand all the values into a single list. Something like this should work:

data.iloc[:, [*list(range(0, 27)), 57, 63, 64]]
Related