Rolf12
Rolf12

Reputation: 771

Combining iloc and loc

I am trying to combine iloc and loc, is there possibility?

Specifically I would like to:

trying

training_set = dataset.loc[:train_size,[list_input_and_y_parameters]].values

gives error message

TypeError: cannot do slice indexing on with these indexers [4275] of

Is there a way to do that?

Many thanks

Upvotes: 15

Views: 11883

Answers (2)

Alexander Myasnikov
Alexander Myasnikov

Reputation: 833

As chaining loc and iloc can cause SettingWithCopyWarning, an option without a need to use Index.get_indexer could be (assuming there are no duplicates in the index):

training_set = dataset.loc[dataset.index[:train_size], ['col1','col2']].values

Upvotes: 4

jezrael
jezrael

Reputation: 863321

You can chain this operation or use only iloc with Index.get_indexer for positions of columns in list:

training_set = dataset.iloc[:train_size].loc[:, ['col1','col2']].values

training_set = dataset.iloc[:train_size, df.columns.get_indexer(['col1','col2'])].values

Upvotes: 22

Related Questions