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


Pandas DataFrame 的 .at 属性用于使用行和列标签访问单个值。“at”属性采用行和列标签数据,以从给定 DataFrame 对象的指定标签位置获取元素。

它将根据行和列标签返回单个值,我们也可以在该特定位置上传值。

如果 DataFrame 中不存在指定的标签,则 .at 属性将引发 KeyError。

示例 1

在下面的示例中,我们使用 Python 字典创建了一个 Pandas DataFrame。列名使用字典中的键进行标记,索引是从 0 到 n-1 的自动生成值。

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame({'A':[1, 2, 3],'B':[7, 8, 6],"C":[5, 6, 2]})

print("DataFrame:")
print(df)

# Access a single value from the DataFrame
result = df.at[0, 'B']
print("Output:",result)

输出

输出如下所示:

DataFrame:
   A  B  C
0  1  7  5
1  2  8  6
2  3  6  2

Output: 7

我们可以在上面的代码块中看到初始化的序列对象和 .at 属性的输出。对于以下行/列对 **df.at[0, 'B']**,.at 属性返回 7。

示例 2

现在,让我们使用 .at 属性在 DataFrame 对象的 [2, 'B'] 位置更新值为“100”,其中 2 表示行索引,“B”表示列名。

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame({'A':[1, 2, 3],'B':[7, 8, 6],"C":[5, 6, 2]})

print("DataFrame:")
print(df)

# by using .at attribute update a value
df.at[2, 'B'] = 100

print("Value 100 updated:")
print(df)

输出

输出如下:

DataFrame:
  A B C
0 1 7 5
1 2 8 6
2 3 6 2

Value 100 updated:
  A   B C
0 1   7 5
1 2   8 6
2 3 100 2

我们已成功在中间列的最后一行 (2, B) 更新值为“100”,我们可以在上面的输出代码块中看到更新后的 DataFrame 对象。

更新于:2022年3月8日

3K+ 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.