Reputation: 1097
I'm working on a data frame that has 246 columns. Specifically, I would like to slice columns 1, 2, 4, 5, 6 and then also select columns 82 to 94, the latter ones being inclusive, all at the same time in one command. I have tried .iloc
and .ix
, but they return syntax errors.
new_df = df.iloc[:, [1, 2 ,4, 5, 6, 82:94]]
new_df = df.iloc[:, [1, 2, 4, 5, 6, 82:94]]
File "<ipython-input-6-012945e7610d>", line 1
new_df = df.iloc[:, [1, 2, 4, 5, 6, 82:94]]
^
SyntaxError: invalid syntax
Same is returned by .ix
too. Is there any other way to do this other than specifying exclusive column indexes (that would be a long command)?
Upvotes: 2
Views: 180
Reputation: 124
To perform select and slicing operations together you can use numpy.r_, which helps in concatenating n number of array slices along an axis.
new_df = df.iloc[:, numpy.r_[1, 2, 4, 5, 6, 82:94]]
Upvotes: 1
Reputation: 3077
I'm afraid you can not mix indexes and slicing like that. A simple workaround is to use range
:
new_df = df.iloc[:, [1, 2 ,4, 5, 6, *range(82,94)]]
Upvotes: 1