Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining iloc and loc

Tags:

python

pandas

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

Specifically I would like to:

  • give integer in the form (:train_size) for the rows values

  • give a list with the column names for the column values (replacing [0,1] in the code below)

    training_set = dataset.iloc[:train_size,[0,1]].values

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

like image 535
Rolf12 Avatar asked Mar 30 '19 20:03

Rolf12


2 Answers

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
like image 141
jezrael Avatar answered Sep 17 '22 07:09

jezrael


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
like image 20
Alexander Myasnikov Avatar answered Sep 21 '22 07:09

Alexander Myasnikov