Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting non-adjacent columns by column number pandas [duplicate]

I have yet to find an answer for this anywhere. I am attempting to select columns number 2 and 86:100. Obviously, I would rather not select them by label.

Intuitively I have tried: df_new = df.iloc[:,[2,86:100]] to no avail.

What is the most efficient way of selecting these columns?

like image 546
a.powell Avatar asked Oct 29 '18 19:10

a.powell


1 Answers

You can use np.r_ to combine slices:

df = pd.DataFrame(np.random.random((3, 10)))

res = df.iloc[:, np.r_[2, 5:10]]

print(res)

          2         5         6         7         8         9
0  0.489923  0.406723  0.085721  0.235617  0.724768  0.398237
1  0.697457  0.565602  0.177975  0.215762  0.377650  0.658344
2  0.116625  0.770128  0.930788  0.367666  0.044933  0.486751
like image 102
2 revs Avatar answered Oct 22 '22 14:10

2 revs