Python Forum

Full Version: "Vlookup" in pandas dataframe
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi! How can I find a value in a column and return it from another column, like a vlookup? Below is an example dataframe.

import pandas as pd
]data = {"Name": ["John", "Michael", "Mary", "Jennifer"], "Age": [25,30,20,25]}
df = pd.DataFrame(data)
df 
Return John's age by searching for his name.
You have some typo's in your code, and if in a module, you need print to display df.

import pandas as pd

data = {"Name": ["John", "Michael", "Mary", "Jennifer"], "Age": [25, 30, 20, 25]}
df = pd.DataFrame(data)
print(df)
There are several tutorials on 'vlookup' with pandas,
here's one: https://www.geeksforgeeks.org/how-to-do-...ng-pandas/
Something like below?

import pandas as pd

data = {"Name": ["John", "Michael", "Mary", "Jennifer"], "Age": [25, 30, 20, 25]}
df = pd.DataFrame(data)

print(df[df.Name == 'John']['Age'][0])  # prints 25
import pandas as pd

data = {"Name": ["John", "Michael", "Mary", "Jennifer"], "Age": [25, 30, 20, 25]}
df = pd.DataFrame(data)
>>> df
       Name  Age
0      John   25
1   Michael   30
2      Mary   20
3  Jennifer   25
>>> 
>>> df.loc[df.Name == 'John', 'Age']
0    25
Name: Age, dtype: int64
More general search against whole DataFrame.
>>> search_name = 'Mar'
>>> df[df.apply(lambda row: row.astype(str).str.contains(search_name, case=False).any(), axis=1)]
   Name  Age
2  Mary   20
>>> df[df.apply(lambda row: row.astype(str).str.contains(search_name, case=False).any(), axis=1)].Age
2    20