Skip to content

Commit 42c8cc1

Browse files
committed
DOC: section in indexing user guide to show use of np.where
1 parent 1f42d45 commit 42c8cc1

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

doc/source/user_guide/indexing.rst

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1158,6 +1158,39 @@ 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+
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+
11611194
.. _indexing.query:
11621195

11631196
The :meth:`~pandas.DataFrame.query` Method

0 commit comments

Comments
 (0)