Home > Back-end >  How to input specific row value, with row number output
How to input specific row value, with row number output

Time:06-26

I've struggled with understanding functions and the task that I am trying to accomplish is creating a function that takes the input from a row-value and outputs the row number.

An example dataset

import pandas as pd
 
data = [['tom', 10], ['nick', 15], ['juli', 14]]

df = pd.DataFrame(data, columns=['Name', 'Age'])

The hope is that I can call any name using a function and the output would be the row number.

Example of what I'm looking for is using the input - "Nick", output would be 1.

CodePudding user response:

Select the rows that have the correct name, then extract the index value of the first row:

df[df['Name'] == 'nick'].index.item()

This outputs:

1

CodePudding user response:

try:

df[df['Name'] == 'nick'].index.to_numpy()

That would give you all the indeces as numpy array where the name is nick :)

CodePudding user response:

Try this:

import pandas as pd

data = [['tom', 10], ['nick', 15], ['juli', 14]]

df = pd.DataFrame(data, columns=['Name', 'Age'])

def find(name):
   return df['Name'].loc[lambda x: x == name].index

print(find('nick'))

Now you could call find('any name') and get an index

  • Related