The question is presented in a somewhat confusing fashion. However, I'm assuming OP has a dataframe setup something like this:
import pandas
data = { 'No': [ 1, 2, 3, 4 ], 'Text': [ 'a', 'ab', 'b', 'bd' ] }
df = pandas.DataFrame( data )
In addition to the df
file, OP has a kpi
list consisting of 'a'
and 'b'
. There is also a mask
variable, which I am assuming was meant to catch all cases where the df.Text
is equal to either 'a'
or 'b
'. This is where the first mistake is. The way OP wrote that line would match cases where the character a
is in any part of the element. In other words 'a' in 'ab'
is True. I suspect, OP wanted that statement to be False, which meant it needs to be written as 'a' == 'ab'
which would be false. I fixed it in the lines below:
kpi = [ 'a', 'b' ]
mask = df['Text'].apply( lambda x: any( item for item in kpi if item.lower() == x ) )
Basically I changed the item.lower() in x
to item.lower() == x
. Next, OP indicated that there should be a new column called matchedItem
, which duplicates the df.Text
when there was a match and '----'
when there was not a match. Given the mask
variable that OP had written, this can be done simply as such:
df[ 'matchedItem' ] = '----'
df.matchedItem[ mask ] = df.Text[ mask ]
In other words, first I set '----'
as the default value for all the elements in column matchedItem
. Next, I copy over the elements from column Text
only for the rows identified in the mask
variable. This results in the following output for print( df )
:
No Text matchedItem
0 1 a a
1 2 ab ----
2 3 b b
3 4 bd ----
There's a number of things that are unclear on the asking of this question (e.g. did OP really want to set mismatches as '----'
? Is No
supposed to be an index or a separate column? etc.), but hopefully this answer will guide OP towards the desired result.