如何使用 .at 属性访问 Pandas Series 中的单个值?


pandas.Series.at 属性用于访问 Series 对象中单个带标签的元素,它与 Pandas 中的 loc 非常相似。“at”属性采用标签数据来获取或设置该特定标签位置的序列值。

它将根据索引标签返回单个值,并且还将在该特定标签位置上传数据。

示例 1

import pandas as pd

# create a sample series
s = pd.Series({'A':12,'B':78,"C":56})

print(s)

print(s.at['A'])

解释

在以下示例中,我们使用 Python 字典创建了一个序列,并且索引将使用字典中的键进行标记。这里,“A”是 s.at['A'] 中的标签,用于表示值的索引位置。

输出

A    12
B    78
C    56
dtype: int64

Output:
12

在上面的代码块中,我们可以看到初始化的序列对象和 at 属性的输出。

示例 2

import pandas as pd

# create a sample series
s = pd.Series([2,4,6,8,10])

print(s)

s.at[0]

解释

我们初始化了一个没有索引的 Series 对象。如果未提供索引,我们可以认为我们的序列对象的索引从 0 开始,以 1 为步长递增到 n-1。

输出

0    2
1    4
2    6
3    8
4    10
dtype: int64

上面代码块中显示了索引位置“0”处的值,即“2”。

示例 3

import pandas as pd

# create a sample series
s = pd.Series({'A':12,'B':78,"C":56})

print(s)

s.at['A'] = 100

print("Updated value at index 'A' ")
print(s)

解释

现在让我们使用 at 属性更新序列对象中位于标签“A”(即索引“A”)处的值为“100”。

输出

A    12
B    78
C    56
dtype: int64

Updated value at index 'A'
A    100
B    78
C    56
dtype: int64

我们已成功在标签位置“A”处更新了值为“100”,我们可以在上面的输出代码块中看到这两个序列对象。

更新于: 2022年3月9日

983 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.