[1074] Using an if...else statement within the apply function in pandas
Here's an example of using an if...else
statement within the apply
function in pandas:
Example
-
Import Pandas:
-
Create a Sample DataFrame:
-
Define a Function with
if...else
: -
Apply the Function to the DataFrame:
-
Print the Result:
Explanation
-
Importing Pandas: First, we import the pandas library.
-
Creating a Sample DataFrame: We create a sample DataFrame
df
with columns 'A' and 'B'. -
Defining a Function with
if...else
: The functioncategorize
takes a row as input and usesif...else
statements to categorize the values in column 'A' as 'High', 'Medium', or 'Low'. -
Applying the Function: We use the
apply
method to apply thecategorize
function to each row of the DataFrame, specifyingaxis=1
to indicate that the function should be applied row-wise. The results are stored in a new column 'Category'. -
Printing the Result: Finally, we print the DataFrame to see the new 'Category' column.
Output
After running the code, your DataFrame will look like this:
This example demonstrates how to use if...else
within the apply
function to categorize data based on specific conditions. Give it a try, and let me know if you need any further assistance!