Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use loc to select a range of columns plus a column outside of the range?

Suppose I want to select a range of columns from a dataframe: Call them 'column_1' through 'column_60'. I know I could use loc like this: df.loc[:, 'column_1':'column_60'] That will give me all rows in columns 1-60.

But what if I wanted that range of columns plus 'column_81'. This doesn't work: df.loc[:, 'column_1':'column_60', 'column_81']

It throws a "Too many indexers" error. Is there another way to state this using loc? Or is loc even the best function to use in this case?

Many thanks.

like image 424
ResearchRn Avatar asked Jun 01 '18 16:06

ResearchRn


1 Answers

How about

df.loc[:, [f'column_{i}' for i in range(1, 61)] + ['column_81']]

or

df.reindex([f'column_{i}' for i in range(1, 61)] + ['column_81'], axis=1)

if you want to fill missing columns, if there are, with default NaN values.

like image 176
tarashypka Avatar answered Oct 06 '22 08:10

tarashypka