PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 6, 2022

[FIXED] How to make a new list by comparing pandas Dataframe Columns with Set

 November 06, 2022     conditional-statements, database, pandas, python, set     No comments   

Issue

I have already a set named "bad_outcomes" and a dataframe where a column name is "Outcome".

Using the "Outcome", I want to create a list where the element is 0 if the corresponding row in Outcome is in the set bad_outcomes; otherwise, it's 1.

Then I want to assign it to the variable 'landing_class'.

I have written this one:

landing_class = []

if df['Outcome'].isin(set(bad_outcomes)):
  landing_class.append(0)
else:
  landing_class.append(1)

It's not working. I have got an error.

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Solution

First, the return of this condition is df['Outcome'].isin(set(bad_outcomes)) is a series of true and false values like that if {true, true, false,....} and that is invalid input to if-statement. In order to solve this problem, you need to use one of the functions such as all() or any().

But adding any or all only solves the error but it does not achieve your goal.

You have three solutions:

First Solution:

for i in df['Outcome']:
    if i in set(bad_outcomes):
        landing_class.append(0)
    else:
        landing_class.append(1) 

Second Solution:

landing_class = np.where(df['Outcome'].isin(set(bad_outcomes)), 0, 1)

Third Solution:

landing_class  = list(~df['Outcome'].isin(set(bad_outcomes))*1)


Answered By - user16310106
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,206,114

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing