case statement in pandas

Solutions on MaxInterview for case statement in pandas by the best coders in the world

showing results for - "case statement in pandas"
Klara
24 Jul 2018
1# If the row value in column 'is_blue' is 1 
2# Change the row value to 'Yes' 
3# otherwise change it to 'No'
4df['is_blue'] = df['is_blue'].apply(lambda x: 'Yes' if (x == 1) else 'No') 
5# or you can use np.where
6df['is_blue'] = np.where(df['is_blue'] == 1, 'Yes', 'No')
7# You can also use mapping to accomplish the same result
8# Warning: Mapping only works once on the same column creates NaN's otherwise
9df['is_blue'] = df['is_blue'].map({0: 'No', 1: 'Yes'})  
Enzo
19 Apr 2017
1df['c'] = np.select(
2[
3    (df['a'].isnull() & (df['b'] == 0))
4], 
5[
6    1
7], 
8default=0 )
9