Ways to apply an if condition in Pandas DataFrame
Generally on a Pandas DataFrame the if condition can be applied either column-wise, row-wise, or on an individual cell basis. The further document illustrates each of these with examples.
First of all we shall create the following DataFrame :
Example 1 : if condition on column values (tuples) : The if condition can be applied on column values like when someone asks for all the items with the MRP <=2000 and Discount >0 the following code does that. Similarly, any number of conditions can be applied on any number of attributes of the DataFrame.
Example 2 : if condition on row values (tuples) : This can be taken as a special case for the condition on column values. If a tuple is given (Sofa, 5000, 20) and finding it in the DataFrame can be done like :
Example 3 : Using Lambda function : Lambda function takes an input and returns a result based on a certain condition. It can be used to apply a certain function on each of the elements of a column in Pandas DataFrame. The below example uses the Lambda function to set an upper limit of 20 on the discount value i.e. if the value of discount > 20 in any cell it sets it to 20.
Example 4 : Using
loc() function : Both
loc() function are used to extract the sub DataFrame from a DataFrame. The sub DataFrame can be anything spanning from a single cell to the whole table.
iloc() is generally used when we know the index range for the row and column whereas
loc() is used on a label search.
The below example shows the use of both of the functions for imparting conditions on the Dataframe. Here a cell with index [2, 1] is taken which is the Badminton product’s MRP.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course