@@ -1158,6 +1158,39 @@ Mask
1158
1158
s.mask(s >= 0 )
1159
1159
df.mask(df >= 0 )
1160
1160
1161
+ .. _indexing.np_where :
1162
+
1163
+ Setting with enlargement conditionally using :func: `numpy `
1164
+ ----------------------------------------------------------
1165
+
1166
+ An alternative to :meth: `~pandas.DataFrame.where ` is to use :func: `numpy.where `.
1167
+ Combined with setting a new column, you can use it to enlarge a dataframe where the
1168
+ values are determined conditionally.
1169
+
1170
+ When you have two choices to choose from, say in the following dataframe, set the color
1171
+ to 'green' when the second column has 'Z'. You can do the following:
1172
+
1173
+ .. ipython :: python
1174
+
1175
+ df = pd.DataFrame({' col1' :list (' ABBC' ), ' col2' :list (' ZZXY' )})
1176
+ df[' color' ] = np.where(df[' col2' ] == ' Z' , ' green' , ' red' )
1177
+ df
1178
+
1179
+ If you have more than one conditions, you can use :func: `numpy.select ` to achieve that.
1180
+ Say corresponding to three conditions there are three choice of colors, with a fourth
1181
+ color as a fallback, you can do the following.
1182
+
1183
+ .. ipython :: python
1184
+
1185
+ conditions = [
1186
+ (df[' col2' ] == ' Z' ) & (df[' col1' ] == ' A' ),
1187
+ (df[' col2' ] == ' Z' ) & (df[' col1' ] == ' B' ),
1188
+ (df[' col1' ] == ' B' )
1189
+ ]
1190
+ choices = [' yellow' , ' blue' , ' purple' ]
1191
+ df[' color' ] = np.select(conditions, choices, default = ' black' )
1192
+ df
1193
+
1161
1194
.. _indexing.query :
1162
1195
1163
1196
The :meth: `~pandas.DataFrame.query ` Method
0 commit comments