pandasDataFrame.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 属性的输出。.at 属性为以下行/列对df.at[0, 'B']返回 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("值 100 更新:") print(df)输出结果
输出如下 -
DataFrame: A B C 0 1 7 5 1 2 8 6 2 3 6 2 值 100 更新: A B C 0 1 7 5 1 2 8 6 2 3 100 2
我们已经成功更新了中间列(2,B)最后一行的值“100”,我们可以在上面的输出块中看到更新后的 DataFrame 对象。