How to create a new data frame by matching elements in a list with another data frame?

67 views Asked by At

Match elements present in list on dataframe and create a new result dataframe

I have a list like below:

newlist = ["email","common name"]

The data frame is like below:

DisplayName Column B
firstname givenName
lastname sn
email mail

How can I search for list values present in dataframe and then create a new dataframe like below:

df[value] = email + '='+ mail

Example is below:

| DisplayName    | Column B | Value              |
|--------------- |--------- | -------------------|
|firstname       | givenName| firstname=givenName|
|lastname        | sn       | lastname=sn        |
|email           | mail     | email=mail         |
2

There are 2 answers

1
Archil Odishelidze On

Import the required libraries: Usually, you would need to import libraries such as Pandas to work with data frames. Make sure you have the necessary libraries installed.

import pandas as pd

Create a list of elements: Define a list containing the elements you want to match with the data frame.

elements_list = ['element1', 'element2', 'element3']

Create the data frame: Create a data frame using the pd.DataFrame() function or load an existing data frame from a file.

Create a sample data frame

data = {'Column1': ['element1', 'element2', 'element3', 'element4', 'element5'], 'Column2': [1, 2, 3, 4, 5]} df = pd.DataFrame(data)

0
Andrej Kesely On

If I understand you correctly, you want to use DataFrame.isin:

newlist = ["email","lastname"]

new_df = df[df['DisplayName'].isin(newlist)].copy()
new_df['Value'] = new_df['DisplayName'] + '=' + new_df['Column B']

print(new_df)

Prints:

  DisplayName Column B        Value
1    lastname       sn  lastname=sn
2       email     mail   email=mail