Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Write a program in Python to find the minimum age of an employee id and salary in a given DataFrame
Finding the employee with the minimum age in a DataFrame is a common data analysis task. We can use pandas boolean indexing to filter rows where the age equals the minimum age value.
Problem Statement
Given a DataFrame with employee data (Id, Age, Salary), we need to find the Id and Salary of the employee with the minimum age.
Input DataFrame
Id Age Salary 0 1 27 40000 1 2 22 25000 2 3 25 40000 3 4 23 35000 4 5 24 30000 5 6 32 30000 6 7 30 50000 7 8 28 20000 8 9 29 32000 9 10 27 23000
Expected Output
Id Salary 1 2 25000
Solution
To solve this problem, we follow these steps:
Create a DataFrame with employee data
Find rows where Age equals the minimum age using boolean indexing
Select only the Id and Salary columns from the filtered result
Step-by-Step Approach
First, we filter rows where the age equals the minimum age ?
result = df[df['Age'] == df['Age'].min()]
Then, we select only the required columns ?
result[['Id', 'Salary']]
Complete Example
import pandas as pd
# Create DataFrame with employee data
data = [[1,27,40000],[2,22,25000],[3,25,40000],[4,23,35000],[5,24,30000],
[6,32,30000],[7,30,50000],[8,28,20000],[9,29,32000],[10,27,23000]]
df = pd.DataFrame(data, columns=['Id', 'Age', 'Salary'])
print("DataFrame is:")
print(df)
# Find employee with minimum age
result = df[df['Age'] == df['Age'].min()]
print("\nEmployee with minimum age (Id and Salary):")
print(result[['Id', 'Salary']])
DataFrame is: Id Age Salary 0 1 27 40000 1 2 22 25000 2 3 25 40000 3 4 23 35000 4 5 24 30000 5 6 32 30000 6 7 30 50000 7 8 28 20000 8 9 29 32000 9 10 27 23000 Employee with minimum age (Id and Salary): Id Salary 1 2 25000
How It Works
The solution uses pandas boolean indexing:
df['Age'].min()finds the minimum age value (22)df['Age'] == df['Age'].min()creates a boolean maskdf[boolean_mask]filters rows where the condition is Trueresult[['Id', 'Salary']]selects specific columns from the filtered result
Conclusion
Use boolean indexing with df['Age'] == df['Age'].min() to find rows with minimum age. Select specific columns using double square brackets to get the final result with Id and Salary information.
