Geng
Geng

Reputation: 11

Why can't I access a single element in Dataframe in Pandas using only brackets?

I understand both of the following ways are allowed:

  1. to access a single column: df['rowA']
  2. to access a few rows: df[3:5]

But df[3:5, 'rowA'], or df[7, 9], gives an exception (TypeError: unhashable type: 'slice'). What's the rationale behind that?

Upvotes: 1

Views: 854

Answers (2)

Anton vBR
Anton vBR

Reputation: 18916

You can chain them too, a combo of getting column and slice. The order is irrelevant.

df['rowA'][3:5]

Or:

df[3:5]['rowA']

Upvotes: 0

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210852

instead of df[3:5, 'rowA'] use:

df.loc[df.index[3:5], 'rowA']

instead of df[7, 9] use:

df.iloc[[7,9]]

Please read official Pandas docs about indexing and selecting data

Upvotes: 1

Related Questions