How to Lookup From One of Multiple Columns Based on Value in Pandas

Preet Sanghavi Feb 02, 2024
How to Lookup From One of Multiple Columns Based on Value in Pandas

This tutorial will learn how to perform lookup operations in Pandas.

Steps to Lookup From One of the Multiple Columns Based on a Value in Pandas

The following are the steps to lookup from one of the multiple columns based on a value in a Pandas dataframe.

Import Pandas

We will now import essential libraries that we will need to get started.

import pandas as pd

Create Pandas DataFrame

We’ll create a sample dataframe that we will use to perform the lookup process.

data = {
    "Year": ["2000", "2001", "2002", "2003"],
    "data": ["a", "b", "c", "d"],
    "a": [1, 2, 3, 4],
    "b": [5, 6, 7, 8],
    "c": [9, 10, 11, 12],
    "d": [13, 14, 15, 16],
}
df = pd.DataFrame(data)

In the above code, we made a dictionary of lists by the name data. We then passed this dictionary to the pd.DataFrame() function to create a Pandas dataframe.

Let us now see how our data frame looks.

print(df)

Output:

   Year data  a  b   c   d
0  2000    a  1  5   9  13
1  2001    b  2  6  10  14
2  2002    c  3  7  11  15
3  2003    d  4  8  12  16

Use the lookup() Function to Lookup From One of the Multiple Columns Based on a Value

We will now perform a lookup from one of the multiple columns based on the column data value. We will use the lookup() function in Pandas to perform the required operation.

df["value"] = df.lookup(df.index, df["data"])

We added a new column named value in the above code, which contains the lookup value added by the lookup() function. In the lookup function, we pass the column name for whose index value we want to find the lookup value in the following columns.

We now print the updated data frame with the newly added column value with the lookup value.

print(df)

Output:

   Year data  a  b   c   d  value
0  2000    a  1  5   9  13      1
1  2001    b  2  6  10  14      6
2  2002    c  3  7  11  15     11
3  2003    d  4  8  12  16     16

We have successfully added the new column with the lookup value in the above output. Thus, we can successfully find the lookup values in Pandas dataframe with the above method.

Preet Sanghavi avatar Preet Sanghavi avatar

Preet writes his thoughts about programming in a simplified manner to help others learn better. With thorough research, his articles offer descriptive and easy to understand solutions.

LinkedIn GitHub

Related Article - Pandas DataFrame