I am attempting to compare the values within a string to values in a list. If the values match, a third list is addended with either a 1 or 0.
Current attempt is to examine each value within the 2 strings. If the entries within the string match, a hash mark is tallied in a third string (0 or 1). I am unable to make the comparison function work - It's not returning any values.
Recent edit: I cannot link to the assignment page, but i can post an image of the problem.
Code is below:
> #list values
landing_outcomes =['True ASDS 41\nNone None 19\nTrue RTLS 14\nFalse ASDS 6\nTrue Ocean 5\nFalse Ocean 2\nNone ASDS 2\nFalse RTLS 1\nName: Outcome, dtype: int64']
> #string values
bad_outcomes = {'False ASDS', 'False Ocean', 'False RTLS', 'None ASDS', 'None None'}
landing_class = []
> #comparison
if any (x in [landing_outcomes] for x in [bad_outcomes]):
landing_class = 0
else:
landing_class = 1
print (landing_class)
CodePudding user response:
Based on your edit (the image you added)...
landing_outcomes
is a pandas Series (A column from a dataframe)- the index of which is the list of Outcomes
- you want to check the dataframe against the set
- which is the opposite of your question
import pandas as pd
landing_outcomes = pd.Series(
[41, 19, 14, 6, 5, 2, 2, 1],
index=['True ASDS', 'None None', 'True RTLS', 'False ASDS', 'True Ocean', 'False Ocean', 'None ASDS', 'False RTLS'],
name='Outcome'
)
bad_outcomes = {'False ASDS', 'False Ocean', 'False RTLS', 'None ASDS', 'None None'}
print()
print(landing_outcomes)
print()
print(bad_outcomes)
landing_class = (~landing_outcomes.index.isin(bad_outcomes)).astype(int).tolist()
print()
print(landing_class)
That Series object has an isin()
method that returns a new Series with True or False on each row.
Using ~
inverts the boolean values (so giving the result of "is not in").
Casting a boolean to an integer (with astype
) turns those booleans in to 1s and 0s.
Then tolist()
turns the pandas Series into a regular python list.