Reputation: 129
I have a python pandas dataframe like this:
data = ['13,12', '8, 7', '12,1', '7', '2,6']
index = 'a', 'b', 'c', 'd', 'e'
col = ['colnames']
df = pd.DataFrame(data, index=index, columns = col)
df
colnames
a 13,12
b 8, 7
c 12,1
d 7
e 2,6
I want to see if the numbers in the 'colnames' column are in the following list of numbers:
7, 8, 9, 10, 12, 13, 15, 23, 24, 25, 26.
I tried to use the following function to check if this is true and if so, it should return 'good' and otherwise, should return 'poor':
def quality_check(qaulity):
for numbers in str(quality):
if numbers in [7, 8, 9, 10, 12, 13, 15, 23, 24, 25, 26]:
return "good"
else:
return "poor"
df['colnames'].map(quality_check)
The expected results is:
a good
b good
c poor
d good
e poor
However, this is what I am getting:
a poor
b poor
c poor
d poor
e poor
Does anyone know how to do this or a better way to do it? I really appreciate any help. Thanks a lot in advance.
Upvotes: 0
Views: 68
Reputation: 180441
I think you need something like this to check all numbers, your function was not checking all the numbers and was comparing ints
to strings
:
def quality_check(q):
spl = q.split(",") # split to check both numbers
if all(x in ["7", "8", "9", "10", "12", "13", "15", "23", "24", "25", "26"]for x in spl):
return "good"
else:
return "poor"
Outputs:
a good
b good
c poor
d good
e poor
Name: colnames, dtype: object
As soon as all
meets an element that is not in the it will return False.
You can also use sets
to check for subsets
also and map
the elements to ints
:
col = ['colnames']
def quality_check(q):
spl = map(int,q.split(",")) # make all ints and split into individual nums
if set(spl).issubset( [7, 8, 9, 10, 12, 13, 15, 23, 24, 25, 26]):
return "good"
else:
return "poor"
You could use sets with the first example also, the elements do not have to be ints.
Upvotes: 1
Reputation: 362837
It looks like you are comparing strings to integers, which won't work:
>>> for n in '123':
... print n,
... if n in [1, 2, 3]:
... print 'yes'
... else:
... print 'no'
...
1 no
2 no
3 no
Upvotes: 1