Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional writing to xlsx

Tags:

python

pandas

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?

like image 554
Mowgli Avatar asked Jan 21 '26 10:01

Mowgli


2 Answers

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')
like image 174
anky Avatar answered Jan 22 '26 23:01

anky


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
like image 36
Karn Kumar Avatar answered Jan 23 '26 00:01

Karn Kumar



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!