File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change @@ -1158,6 +1158,40 @@ Mask
11581158 s.mask(s >= 0 )
11591159 df.mask(df >= 0 )
11601160
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+ Consider you have two choices to choose from in the following dataframe. And you want to
1171+ set a new column color to 'green' when the second column has 'Z'. You can do the
1172+ following:
1173+
1174+ .. ipython :: python
1175+
1176+ df = pd.DataFrame({' col1' : list (' ABBC' ), ' col2' : list (' ZZXY' )})
1177+ df[' color' ] = np.where(df[' col2' ] == ' Z' , ' green' , ' red' )
1178+ df
1179+
1180+ If you have multiple conditions, you can use :func: `numpy.select ` to achieve that. Say
1181+ corresponding to three conditions there are three choice of colors, with a fourth color
1182+ as a fallback, you can do the following.
1183+
1184+ .. ipython :: python
1185+
1186+ conditions = [
1187+ (df[' col2' ] == ' Z' ) & (df[' col1' ] == ' A' ),
1188+ (df[' col2' ] == ' Z' ) & (df[' col1' ] == ' B' ),
1189+ (df[' col1' ] == ' B' )
1190+ ]
1191+ choices = [' yellow' , ' blue' , ' purple' ]
1192+ df[' color' ] = np.select(conditions, choices, default = ' black' )
1193+ df
1194+
11611195 .. _indexing.query :
11621196
11631197The :meth: `~pandas.DataFrame.query ` Method
You can’t perform that action at this time.
0 commit comments