eliteA92
eliteA92

Reputation: 421

Python Pandas: how to change between selection by label and selection by index

I know we have the method loc[] for selection by label and iloc[] for selection by index. But I am struggling when I want to change from one to other or even mix them.

Let's say we have data of animals and its stats:

import pandas as pd
csv = [
    ['cat', 5, 2, 9],
    ['dog', 7, 8, 6],
    ['fish', 3, 1, 4]
]
df = pd.DataFrame(csv, columns=['animal', 'speed', 'strength', 'agility'])
df = df.set_index('animal')

And now I want to know the dog's strength. I run:

df.loc['dog','strength']

and I get the desired output. But what if now I want to know which indexes are associated to this output?

And the oposite situation. Let's say I know the indexes and I run:

df.iloc[1][1]

but now I want to know which animal and which stat is associated with this result.

In other words, how to know that 'dog' is row = 1 and that 'strength' is column = 1 and viceversa?

Moreover, what if I want to combine labels and indexes. In my example it will something like "get the second column for dog's row". How can I do it?

Thank you.

Upvotes: 0

Views: 90

Answers (2)

Scott Boston
Scott Boston

Reputation: 153500

If you added you indexes/column headers in brackets, you will return a dataframe instead of the scalar value. For example:

df.loc[['dog'],['strength']]

Output:

        strength
animal          
dog            8

OR,

df.iloc[[1],[1]]

Output:

        strength
animal          
dog            8

Upvotes: 1

BENY
BENY

Reputation: 323326

We can using get_indexer

i, j = df.index.get_indexer(['dog']),df.columns.get_indexer(['strength'])
i
Out[522]: array([1], dtype=int64)
j
Out[523]: array([1], dtype=int64)

df.iloc[i,j]
Out[528]: 
        strength
animal          
dog            8

Upvotes: 1

Related Questions