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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With