Pandas 如何获取系列中最大值的位置

Pandas 如何获取系列中最大值的位置

在pandas系列构造函数中,有一个称为argmax()的方法,用于获取系列数据中最大值的位置。

pandas系列是一个单维数据结构对象,具有行索引值。通过使用行索引值,我们可以访问数据。

pandas系列中的argmax()方法用于获取系列对象的最大值的位置索引。argmax方法的输出是一个整数值,表示最大值所在的位置。

示例1

# import pandas package
import pandas as pd
import numpy as np

# create a pandas series
s = pd.Series(np.random.randint(10,100, 10))
print(s)

# Apply argmax function
print('Output of argmax', s.argmax())

解释

让我们创建一个pandas系列对象,其中包含10个介于10到100之间的随机整数值,并应用argmax()函数来获取系列值中最大值的位置。

输出

0 81
1 94
2 75
3 13
4 17
5 42
6 45
7 29
8 25
9 59
dtype: int32

Output of argmax: 1

pandas series对象的argmax()方法对于下面的示例返回一个整数值“1”,该整数值表示给定系列元素的最大值的位置。

示例2

import pandas as pd
import numpy as np

# creating pandas Series object
series = pd.Series({'Black':10, 'White':29,'Red':82, 'Blue':56,'Green':67})
print(series)

# Apply argmax function
print('Output of argmax:',series.argmax())

解释

在下面的示例中,我们使用Python字典创建了一个pandas.Series对象“series”,并且生成的Series具有以整数为数据的带有命名索引标签的。然后,我们将argmax()方法应用于Series对象的数据,以获取最大数值的位置。

输出

Black 10
White 29
Red   82
Blue  56
Green 67
dtype: int64

Output of argmax: 2

argmax()方法的输出对于以下示例是2,这意味着在索引标签“Red”的值具有最大值。

如果最大值在多个位置都可用,那么argmax方法将返回第一行位置作为输出。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程

Pandas 精选笔记