To create a new label in a pandas DataFrame based on a condition for three possible labels in Python, you can use the np.where()
function or the DataFrame.loc[]
method.
Here's an example using np.where()
:
main.py546 chars24 lines
Output:
main.py126 chars7 lines
In the above example, we define three conditions (condition1
, condition2
, condition3
) and three labels (label1
, label2
, label3
).
The np.where()
function checks the conditions sequentially and assigns the corresponding label based on the condition result. If none of the conditions are met, an empty string is assigned to the label. The new label
column is then added to the DataFrame.
Alternatively, here's an example using DataFrame.loc[]
:
main.py531 chars25 lines
The output will be the same as in the previous example.
Using DataFrame.loc[]
, we assign the corresponding labels to the 'label' column based on the conditions. Each condition is checked separately, and the label is assigned where the condition is true.
Note: Make sure to import the required libraries (pandas
and numpy
) before using them in your code.
gistlibby LogSnag