Hướng dẫn get max value python

DataFrame.max(axis=NoDefault.no_default, skipna=True, level=None, numeric_only=None, **kwargs)[source]

Return the maximum of the values over the requested axis.

Nội dung chính

  • Definition and Usage
  •  Return Value
  • Pandas max() function
  • 1. Max value in a single pandas column
  • 2. Max value in two pandas columns
  • 3. Max value for each column in the dataframe
  • 4. Max value between two pandas columns
  • 5. Max value in the entire dataframe
  • How do you find the maximum and minimum of a column in Python?
  • How do you find the maximum index of a DataFrame?
  • How do you find the top 5 values in Python?
  • How do you get top 10 values in pandas?

If you want the index of the maximum, use idxmax. This is the equivalent of the numpy.ndarray method argmax.

Parametersaxis{index (0), columns (1)}

Axis for the function to be applied on.

skipnabool, default True

Exclude NA/null values when computing the result.

levelint or level name, default None

If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series.

numeric_onlybool, default None

Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.

**kwargs

Additional keyword arguments to be passed to the function.

ReturnsSeries or DataFrame (if level specified)

Examples

>>> idx = pd.MultiIndex.from_arrays([
...     ['warm', 'warm', 'cold', 'cold'],
...     ['dog', 'falcon', 'fish', 'spider']],
...     names=['blooded', 'animal'])
>>> s = pd.Series([4, 2, 0, 8], name='legs', index=idx)
>>> s
blooded  animal
warm     dog       4
         falcon    2
cold     fish      0
         spider    8
Name: legs, dtype: int64

❮ DataFrame Reference


Example

Return the highest value for each column:

import pandas as pd

data = [[10, 18, 11], [13, 15, 8], [9, 20, 3]]

df = pd.DataFrame(data)

print(df.max())

Try it Yourself »


Definition and Usage

The max() method returns a Series with the maximum value of each column.

By specifying the column axis (axis='columns'), the max() method searches column-wise and returns the maximum value for each row.


Syntax

dataframe.max(axis, skipna, level, numeric_only, kwargs)


Parameters

The axis, skipna, level, numeric_only parameters are keyword arguments.

ParameterValueDescription
axis 0
1
'index'
'columns'
Optional, Which axis to check, default 0.
skip_na True
False
Optional, default True. Set to False if the result should NOT skip NULL values
level Number
level name
Optional, default None. Specifies which level ( in a hierarchical multi index) to check along
numeric_only None
True
False
Optional. Specify whether to only check numeric values. Default None
kwargs   Optional, keyword arguments. These arguments has no effect, but could be accepted by a NumPy function

 Return Value

A Series with the maximum values.

If the level argument is specified, this method will return a DataFrame object.

This function does NOT make changes to the original DataFrame object.


❮ DataFrame Reference


Pandas dataframes are great for analyzing and manipulating data. In this tutorial, we will look at how to get the max value in one or more columns of a pandas dataframe with the help of some examples.

Pandas max() function

Hướng dẫn get max value python

You can use the pandas max() function to get the maximum value in a given column, multiple columns, or the entire dataframe. The following is the syntax:

# df is a pandas dataframe

# max value in a column
df['Col'].max()
# max value for multiple columns
df[['Col1', 'Col2']].max()
# max value for each numerical column in the dataframe
df.max(numeric_only=True)
# max value in the entire dataframe
df.max(numeric_only=True).max()

It returns the maximum value or values depending on the input and the axis (see the examples below).

Examples

Let’s look at some use-case of the pandas max() function. First, we’ll create a sample dataframe that we will be using throughout this tutorial.

import numpy as np
import pandas as pd

# create a pandas dataframe
df = pd.DataFrame({
    'Name': ['Neeraj Chopra', 'Jakub Vadlejch', 'Vitezslav Vesely', 'Julian Weber', 'Arshad Nadeem'],
    'Country': ['India', 'Czech Republic', 'Czech Republic', 'Germany', 'Pakistan'],
    'Attempt1': [87.03, 83.98, 79.79, 85.30, 82.40],
    'Attempt2': [87.58, np.nan, 80.30, 77.90, np.nan],
    'Attempt3': [76.79, np.nan, 85.44, 78.00, 84.62],
    'Attempt4': [np.nan, 82.86, np.nan, 83.10, 82.91],
    'Attempt5': [np.nan, 86.67, 84.98, 85.15, 81.98],
    'Attempt6': [84.24, np.nan, np.nan, 75.72, np.nan]
})
# display the dataframe
df

Output:

Here we created a dataframe containing the scores of the top five performers in the men’s javelin throw event final at the Tokyo 2020 Olympics. The attempts represent the throw of the javelin in meters.

1. Max value in a single pandas column

To get the maximum value in a pandas column, use the max() function as follows. For example, let’s get the maximum value achieved in the first attempt.

# max value in Attempt1
print(df['Attempt1'].max())

Output:

87.03

We get 87.03 meters as the maximum distance thrown in the “Attemp1”

Note that you can get the index corresponding to the max value with the pandas idxmax() function. Let’s get the name of the athlete who threw the longest in the first attempt with this index.

# index corresponding max value
i = df['Attempt1'].idxmax()
print(i)
# display the name corresponding this index
print(df['Name'][i])

Output:

0
Neeraj Chopra

You can see that the max value corresponds to “Neeraj Chopra”.

2. Max value in two pandas columns

You can also get the max value of multiple pandas columns with the pandas min() function. For example, let’s find the maximum values in “Attempt1” and “Attempt2” respectively.

# get max values in columns "Attempt1" and "Attempt2"
print(df[['Attempt1', 'Attempt2']].max())

Output:

Attempt1    87.03
Attempt2    87.58
dtype: float64

Here, created a subset dataframe with the columns we wanted and then applied the max() function. We get the maximum value for each of the two columns.

3. Max value for each column in the dataframe

Similarly, you can get the max value for each column in the dataframe. Apply the max function over the entire dataframe instead of a single column or a selection of columns. For example,

# get max values in each column of the dataframe
print(df.max())

Output:

Name        Vitezslav Vesely
Country             Pakistan
Attempt1               87.03
Attempt2               87.58
Attempt3               85.44
Attempt4                83.1
Attempt5               86.67
Attempt6               84.24
dtype: object

We get the maximum values in each column of the dataframe df. Note that we also get max values for text columns based on their string comparisons in python.

If you only want the max values for all the numerical columns in the dataframe, pass numeric_only=True to the max() function.

# get max values of only numerical columns
print(df.max(numeric_only=True))

Output:

Attempt1    87.03
Attempt2    87.58
Attempt3    85.44
Attempt4    83.10
Attempt5    86.67
Attempt6    84.24
dtype: float64

4. Max value between two pandas columns

What if you want to get the maximum value between two columns?
You can do so by using the pandas max() function twice. For example, let’s get the maximum value considering both “Attempt1” and “Attempt2”.

# max value over two columns
print(df[['Attempt1', 'Attempt2']].max().max())

Output:

87.58

We get 87.58 as the maximum distance considering the first and the second attempts together.

5. Max value in the entire dataframe

You can also get the single biggest value in the entire dataframe. For example, let’s get the biggest value in the dataframe df irrespective of the column.

# mav value over the entire dataframe
print(df.max(numeric_only=True).max())

Output:

87.58

Here we apply the pandas max() function twice. First time to get the max values for each numeric column and then to get the max value among them.

For more on the pandas max() function, refer to its documentation.

With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having pandas version 1.0.5


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

  • Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

    View all posts

How do you find the maximum and minimum of a column in Python?

“find max and min values in python column” Code Answer's.

min_vals = df[["A","B","C"]]. min() #can add how much ever columns..

max_vals = df[["D","E","F"]]. max() #can add how much ever columns..

min_val = df["Column"]. min().

max_val = df["Column"]. max().

min_val = df[:]. min().

max_val = df[:]. max().

How do you find the maximum index of a DataFrame?

idxmax() function returns index of first occurrence of maximum over requested axis. While finding the index of the maximum value across any index, all NA/null values are excluded. Example #1: Use idxmax() function to function to find the index of the maximum value along the index axis.

How do you find the top 5 values in Python?

Python's Pandas module provide easy ways to do aggregation and calculate metrics. Finding Top 5 maximum value for each group can also be achieved while doing the group by. The function that is helpful for finding the Top 5 maximum value is nlargest().

How do you get top 10 values in pandas?

How to Get Top 10 Highest or Lowest Values in Pandas.

Step 1: Create Sample DataFrame. ... .

Step 2: Get Top 10 biggest/lowest values for single column. ... .

Step 3: Get Top 10 biggest/lowest values - duplicates. ... .

Step 4: Get Top N values in multiple columns. ... .

Step 5: How do nsmallest and nlargest work..