[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
dfwith columns 'A' and 'B'. -
Defining a Function with
if...else: The functioncategorizetakes a row as input and usesif...elsestatements to categorize the values in column 'A' as 'High', 'Medium', or 'Low'. -
Applying the Function: We use the
applymethod to apply thecategorizefunction to each row of the DataFrame, specifyingaxis=1to 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!
浙公网安备 33010602011771号