TransWikia.com

Comparing a column value to list of values and if it contains the value then assigning that list value to new Column

Data Science Asked on September 27, 2021

Column
enter image description here

and wanted to check with this list

list_CI = ['Application', 'Server & Storage', 'Active Directory',
       'Please Select Value', 'SAP', 'WPS-Core Infra Services',
       'Workplace', 'WPS-Telecoms', 'Citrix', 'Networks',
       'WPS-Connectivity Support', 'WPS-Groupware', 'WPS-Smarthands',
       'Networks & Telecomms']

I tried to apply lambda but fail. How can solve through regex or any other method?

Please hint and shed some light. Thanks.

3 Answers

This is the solution, after 4-5 attempt this code solves the problem

 def extractServiceName(x):
    if x in  list_CI:
        return x
    else:
        return ''

Sample_data['Extracted_New_CI'] = Sample_data['CI Name'].apply(lambda x : extractServiceName(x))

Correct answer by Taylor on September 27, 2021

I would recommend using "apply" method in pandas, which allows you to apply a function along an axis of the DataFrame.

So, what I did is to write a function that checks whether a given row of data frame contains one of the values in the list or not. If it contains one of the values it returns that value; otherwise, it returns None.

Then, I applied this function along axis 1 of the data frame using "apply" method.

Also, I tried to use the lower case of each word in the list and each row to prevent any consequent issues; you can remove that if the capital or lower case matter in your case.

def check_value(x):
    for i in list_CI:
        if i.lower() in x.lower():
           return i
    return None

df['new_col'] = df.apply(lambda x['CI Name']: check_value(x), axis = 1)

Answered by nimar on September 27, 2021

You could try this if this is simple and more readable:

Sample_data['Extracted_New_CI'] = Sample_data[Sample_data['CI Name'].isin(list_CI)]

Answered by ravibeli on September 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP