1

I have a dataframe with 3 columns and I need to get the index of the row that match the values with 2 columns.

For example, the dataframe below:

Name     City   Country
Pietro   Roma   Italy
Maria    Milan  Italy
Pietro   NY     USA

In this case, I need to get the index of Pietro|Roma|Italy, seaching for Name and City columns only.

I tried doing the code below, but it returns all the rows that matches the 2 columns.

idx = np.where(dataframe[dataframe["Name"] == 'Pietro'],dataframe[dataframe["City"] == 'Roma'])

But it returns an array of indexes [[0,2],[0]] and I need to return index 0 that is where I have Name = 'Pietro' and City = 'Roma'

Updated with Solution

The solution is:

dataframe.index[(dataframe["Name"] == 'Pietro')&(dataframe["City"] == 'Roma')][0]

1 Answer 1

4

Using

dataframe.index[(dataframe["Name"] == 'Pietro')&(dataframe["City"] == 'Roma')]
Sign up to request clarification or add additional context in comments.

2 Comments

This is correct, but returns the index object, (Int64Index([0], dtype='int64'). If you want just the value of the index, add [0] to the end
It worked combining answers: dataframe.index[(dataframe["Name"] == 'Pietro')&(dataframe["City"] == 'Roma')] [0]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.