Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to compare two cells with strings in pandas?

I have a pandas dataframe as follows:

FIRST GOAL        WINNER

Algeria           brazil
Argentina      Argentina
Japan            Germany
brazil             brazil
france            France

i want to check if the first goal scorer is the winner of the game. can some one help?

like image 850
Ravi Teja Avatar asked Jul 04 '26 02:07

Ravi Teja


2 Answers

You need:

df['is_winnder'] = df['FIRST GOAL'].str.lower() == df['WINNER'].str.lower()

Output:

    FIRST GOAL  WINNER   is_winnder
0    Algeria     brazil       False
1  Argentina  Argentina        True
2      Japan    Germany       False
3     brazil     brazil        True
4     france     France        True
like image 64
harvpan Avatar answered Jul 06 '26 17:07

harvpan


IIUC:
You need to compare france to France which requires normalization of the string. We can make all letters UPPER, lower, or Title. I went with lower.

nunique

Stack, then use str.lower to normalize capitalization.
In this answer, I stacked the dataframe in order to only have to call str.lower once on the stacked Series object. I then determined the number of unique values per the first level of the index, which were our old rows. If the number of unique values is equal to one, then the columns must have been equal.

df.stack().str.lower().groupby(level=0).nunique().eq(1)

0    False
1     True
2    False
3     True
4     True
dtype: bool

Or

df.assign(is_winner=df.stack().str.lower().groupby(level=0).nunique().eq(1))

  FIRST GOAL     WINNER  is_winner
0    Algeria     brazil      False
1  Argentina  Argentina       True
2      Japan    Germany      False
3     brazil     brazil       True
4     france     France       True

Series.str.lower

This is virtually identical to Harv Ipan's answer with the exception that I added str.lower().

df.assign(is_winner=df['FIRST GOAL'].str.lower() == df['WINNER'].str.lower())

applymap

This is succinct. One call using applymap that uses str.lower. Then I got tricky with unpacking the values array into an eq operator.

from operator import eq

df.assign(winner=eq(*df.applymap(str.lower).values.T))
like image 37
piRSquared Avatar answered Jul 06 '26 17:07

piRSquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!