Reputation: 12826
I have the following data frame:
A | Date1 | Date2
10 | 2/2/2016 | 3/2/2016
11 | 1/5/2016 | 1/5/2016
12 | 2/3/2016 | 2/3/2016
13 | 1/5/2016 | 3/2/2013
If the value in Date1 is equal to Date2, I want to make the value in column A as 0. End result:
A | Date1 | Date2
10 | 2/2/2016 | 3/1/2016
0 | 1/5/2016 | 1/5/2016
0 | 2/3/2016 | 2/3/2016
13 | 1/5/2016 | 3/2/2013
I want to do this without writing a for loop. Can I use apply?
You can recreate my df:
df = pd.DataFrame([[10, "2/2/2016", "3/2/2016" ] , [11, "1/5/2016", "1/5/2016"] , [12 , "2/3/2016" , "2/3/2016" ] , [13, "1/5/2016", "3/2/2013"]])
df.columns = ['A','B','C']
Upvotes: 1
Views: 59
Reputation: 294258
Using jezrael's setup
import pandas as pd
df = pd.DataFrame([[10, "2/2/2016", "3/2/2016" ] ,
[11, "1/5/2016", "1/5/2016"] ,
[12 , "2/3/2016" , "2/3/2016" ] ,
[13, "1/5/2016", "3/2/2013"]])
df.columns = ['A','B','C']
loc
df.loc[df.B == df.C, 'A'] = 0
print df
A B C
0 10 2/2/2016 3/2/2016
1 0 1/5/2016 1/5/2016
2 0 2/3/2016 2/3/2016
3 13 1/5/2016 3/2/2013
Upvotes: 1
Reputation: 862641
Use mask
:
import pandas as pd
df = pd.DataFrame([[10, "2/2/2016", "3/2/2016" ] ,
[11, "1/5/2016", "1/5/2016"] ,
[12 , "2/3/2016" , "2/3/2016" ] ,
[13, "1/5/2016", "3/2/2013"]])
df.columns = ['A','B','C']
print (df)
A B C
0 10 2/2/2016 3/2/2016
1 11 1/5/2016 1/5/2016
2 12 2/3/2016 2/3/2016
3 13 1/5/2016 3/2/2013
df['A'] = df.mask(df.B == df.C, 0)
print (df)
A B C
0 10 2/2/2016 3/2/2016
1 0 1/5/2016 1/5/2016
2 0 2/3/2016 2/3/2016
3 13 1/5/2016 3/2/2013
Solution with where
:
df['A'] = df.where(df.B != df.C, 0)
print (df)
A B C
0 10 2/2/2016 3/2/2016
1 0 1/5/2016 1/5/2016
2 0 2/3/2016 2/3/2016
3 13 1/5/2016 3/2/2013
Upvotes: 3