List of Topics:
Location Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Use apply() and unique() for Sample Dataset Using Python

How to Use apply() and unique() for Sample Dataset Using Python

Condition for Using apply() and unique() in Python

  • Description:
    The apply() function in Pandas is used to apply a function along an axis (rows or columns) of a DataFrame or Series. This is useful when you need to perform a custom operation on each row or column.

    The unique() function is used to return the unique values in a DataFrame column or Series. It helps to quickly identify the distinct values present in the data.
Step-by-Step Process
  • Using apply():
    You can use the apply() function to apply any custom function to each row or column of a DataFrame or Series.
    Syntax:
    DataFrame.apply(func, axis=0) where axis=0 applies the function to columns and axis=1 applies it to rows.
  • Using unique():
    The unique() function returns an array of unique values in a particular column or Series.
    Syntax:
    DataFrame['column_name'].unique()
Sample Source Code
  • import pandas as pd

    data = {
    'Employee ID': [1, 2, 3, 4, 5],
    'Department': ['HR', 'IT', 'IT', 'HR', 'Finance'],
    'Age': [25, 30, 28, 35, 40]
    }

    df = pd.DataFrame(data)

    print("Original DataFrame:")
    print(df)

    # 1. Using apply() to create a new column based on a custom function
    df['Age Category'] = df['Age'].apply(lambda x: 'Young' if x < 30 else 'Adult')

    print("\nDataFrame after using apply() to create Age Category:")
    print(df)

    # 2. Using unique() to find the unique departments
    unique_departments = df['Department'].unique()

    print("\nUnique Departments:")
    print(unique_departments)
Screenshots
  • Apply and Unique Function Output