What is the usage of the pandas apply function?

The apply function in pandas is used to perform operations on the data in a DataFrame or Series row by row or column by column. It takes a function as a parameter and applies that function to each row or column of data.

There are two common ways to use the apply function.

  1. Applying a function to each row or column of a DataFrame: you can choose whether to operate on rows or columns by specifying the axis parameter. By default, axis is set to 0, which means applying the function to each column, while axis 1 means applying the function to each row. For example, finding the sum of each column in a DataFrame:
  2. – Bring into the code the pandas library and name it pd.
    – Create a DataFrame named df with columns ‘A’ and ‘B’ containing values 1, 2, 3 and 4, 5, 6 respectively.
    – Define a function sum_column that calculates the sum of a column.
    – Apply the function sum_column to each column in the DataFrame df and print the result.
  3. Output:
  4. Option:
    A has a value of 6 and B has a value of 15, both of type integer.
  5. Apply a function to each element of a DataFrame or each element of a Series: this can be done by specifying the axis parameter as None. For example, squaring each element of a DataFrame.
  6. import the pandas library as pd

    create a DataFrame named df with columns ‘A’ and ‘B’ containing the values [1, 2, 3] and [4, 5, 6] respectively

    define a function named square that squares a given number

    apply the square function element-wise to the DataFrame df and store the result in a new DataFrame called result

    print the result DataFrame

  7. Output:
  8. A: 1, B: 16
    A: 4, B: 25
    A: 9, B: 36

It is important to note that the apply function iterates through each row or column of the data, so when using the apply function, it is advisable to avoid time-consuming operations like loops in order to improve performance.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds