To get a value based on the maximum of another column in Pandas, you can use the following steps:
- Step 1: Import the necessary libraries:
import pandas as pd
- Step 2: Create a sample DataFrame:
data = {'Name': ['John', 'Emma', 'James', 'Anna'],
'Age': [35, 28, 42, 37],
'Salary': [50000, 60000, 55000, 65000]}
df = pd.DataFrame(data)
- Step 3: Find the maximum value of the ‘Salary’ column:
max_salary = df['Salary'].max()
- Step 4: Get the corresponding value from another column based on the maximum ‘Salary’:
max_salary_name = df.loc[df['Salary'] == max_salary, 'Name'].values[0]
- Step 5: Print the result:
print("The person with the highest salary is:", max_salary_name)
In this example, we have created a DataFrame with three columns: ‘Name’, ‘Age’, and ‘Salary’. We then found the maximum value of the ‘Salary’ column using the max()
function. Finally, we used the loc
function to get the corresponding value from the ‘Name’ column based on the maximum ‘Salary’. The result will be printed as “The person with the highest salary is: Anna”.