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 = lincoln@gmx.net
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 lincoln@gmail.net
2 obama@gmail.net
3 trump@gmail.net
4 franklin@gmail.net
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 lincoln@gmail.net on
2 obama@gmail.net on
3 trump@gmail.net off
4 franklin@gmail.net on
How do I achieve this?
filter the Protection
column where the email is not 'trump@gmail.net'
and assign them 'on' and vice versa.
df.loc[df['Email']!='trump@gmail.net', 'Protection']='on'
df.loc[df['Email']=='trump@gmail.net', 'Protection']='off'
using np.where
:
df['Protection'] = np.where((df['Email']!='trump@gmail.net'),'on','off')
or:
df['Protection'] = np.where((df['Email']=='trump@gmail.net'),'off','on')
Just another Solution around based on if and else condition:
DataFrame:
>>> df
Email Protection
0 lincoln@gmail.net
1 obama@gmail.net
2 trump@gmail.net
3 franklin@gmail.net
Result:
>>> df['Protection'] = ['On' if x !="trump@gmail.net" else 'Off' for x in df['Email']]
# df['Protection'] = ['Off' if x =="trump@gmail.net" else 'On' for x in df['Email']]
>>> df
Email Protection
0 lincoln@gmail.net On
1 obama@gmail.net On
2 trump@gmail.net Off
3 franklin@gmail.net On
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.