Mowgli
Mowgli

Reputation: 257

Conditional writing to xlsx

Folks,

I'm currently working with a huge excel sheet, python 3.7.1 and pandas 0.23.4. My task is to write to cells based on conditional matching. Something like this:

val = [email protected]
if val in Cell_3A:
    write something to Cell_3B

To make a complete example, let's say the following is my dataframe:

    Email               Protection
1   [email protected]
2   [email protected]
3   [email protected]
4   [email protected]

I know want to write down that all of the emails are protected, except for the email in row 3. So the finished dataframe should look like this:

    Email               Protection
1   [email protected]   on
2   [email protected]     on
3   [email protected]     off
4   [email protected]  on

How do I achieve this?

Upvotes: 2

Views: 379

Answers (2)

anky
anky

Reputation: 75110

filter the Protection column where the email is not '[email protected]' and assign them 'on' and vice versa.

df.loc[df['Email']!='[email protected]', 'Protection']='on'
df.loc[df['Email']=='[email protected]', 'Protection']='off'

using np.where:

df['Protection'] = np.where((df['Email']!='[email protected]'),'on','off')

or:

df['Protection'] = np.where((df['Email']=='[email protected]'),'off','on')

Upvotes: 6

Karn Kumar
Karn Kumar

Reputation: 8826

Just another Solution around based on if and else condition:

DataFrame:

>>> df
                Email Protection
0   [email protected]
1     [email protected]
2     [email protected]
3  [email protected]

Result:

>>> df['Protection'] = ['On' if x !="[email protected]"  else 'Off' for x in df['Email']]
 # df['Protection'] = ['Off' if x =="[email protected]"  else 'On' for x in df['Email']]
>>> df
                Email Protection
0   [email protected]         On
1     [email protected]         On
2     [email protected]        Off
3  [email protected]         On

Upvotes: 3

Related Questions