Home > Mobile >  Pandas: slice by named index using loc, but not include first index
Pandas: slice by named index using loc, but not include first index

Time:12-09

I have a dataframe with named indexes, need to select all above particular index, not including it.

For example:

df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
     index=['cobra', 'viper', 'sidewinder'],
     columns=['max_speed', 'shield'])
max_speed shield
cobra 1 2
viper 4 5
sidewinder 7 8

I need to select df below cobra. So like pseudo code: df.loc['cobra' 1 : ]

CodePudding user response:

There are several ways to go about this:

>>> df.iloc[df.index.tolist().index('cobra') 1:]
            max_speed  shield
viper               4       5
sidewinder          7       8

>>> df.drop('cobra', axis=0)
            max_speed  shield
viper               4       5
sidewinder          7       8

>>> df[df.index != 'cobra']
            max_speed  shield
viper               4       5
sidewinder          7       8

An addition method that @Quang Hoang proposed:

>>> df.iloc[df.index.get_indexer(['cobra'])[0] 1:]
            max_speed  shield
viper               4       5
sidewinder          7       8

CodePudding user response:

try

df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
     index=['cobra', 'viper', 'sidewinder'],
     columns=['max_speed', 'shield'])
print(df.loc[df.index > 'cobra'])

output

            max_speed  shield
viper               4       5
sidewinder          7       8

CodePudding user response:

Selecting without include cobra:

df.iloc[df.index.get_indexer(['cobra'])[0] 2:,:]
  • Related