Home > OS >  Add column value in panda data frame if certain condition is met
Add column value in panda data frame if certain condition is met

Time:02-14

I have two lists:

    required=["api.gotinder.com","data.gotinder.com"]
    not_required=["graph.facebook.com","launches.appsflyer.com"]

If the value in requested_server_name column is in required list then it should be labeled as Required if the value in requested_server_name column is in not_required list then it should be labeled as Not_Required

What I am doing at the moment:

for j in required:
    conditions = [
        (frame['requested_server_name'] == j)
        ]
    values = ["Required"]
    frame['label'] = np.select(conditions, values)

for k in not_required:
    conditions = [
        (frame['requested_server_name'] == k)
        ]
    values = ["Not_Required"]
    frame['label'] = np.select(conditions, values)

What am I doing wrong?? It only populates the label for launches.appsflyer.com.

CodePudding user response:

Create a dict then reverse keys and values to create a mapping dict. Finally use replace to apply the mapping:

d = {'required': ["api.gotinder.com", "data.gotinder.com"],
     'not_required': ["graph.facebook.com", "launches.appsflyer.com"]}

MAP = {v: k for k, l in d.items() for v in l}

frame['label'] = frame['requested_server_name'].replace(MAP)

CodePudding user response:

for j in required:
    frame.loc[frame['requested_server_name'] == j, 'Label'] = "Required"


for k in not_required:
    frame.loc[frame['requested_server_name'] == k, 'Label'] = "Not_Required"
    

This works as well.

  • Related