Pandas at vs. loc:有什么区别

1,587 阅读2分钟

当涉及到选择pandas DataFrame的行和列时,.loc 和.at是两个常用的函数。

下面是这两个函数之间的细微差别:

  • .loc可以接受多个行和列作为输入参数
  • .at只能接受一行和一列作为输入参数。

下面的例子展示了如何在实践中用以下pandas DataFrame使用每个函数。

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                   'points': [18, 22, 19, 14, 14, 11, 20, 28],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
print(df)

  team  points  assists  rebounds
0    A      18        5        11
1    B      22        7         8
2    C      19        7        10
3    D      14        9         6
4    E      14       12         6
5    F      11        9         5
6    G      20        9         9
7    H      28        4        12

例1:如何在Pandas中使用loc

下面的代码显示了如何使用**.loc**来访问DataFrame中位于点数列索引位置0的数值。

#select value located at index position 0 of the points column
df.loc[0, 'points']

18

这将返回一个18的值。

下面的代码显示了如何使用**.loc**来访问索引值0和4之间的行以及列point和assists。

#select rows between index values 0 and 4 and columns 'points' and 'assists'
df.loc[0:4, ['points', 'assists']]

        points	assists
0	18	5
1	22	7
2	19	7
3	14	9
4	14	12

无论我们是想访问一个单一的值还是一组行和列,.loc函数都可以做到。

例2:如何在Pandas中使用at

下面的代码显示了如何使用**.at** 来访问位于point列索引位置0的DataFrame中的值。

#select value located at index position 0 of the points column
df.at[0, 'points']

18

这将返回一个18的值。

然而,假设我们试图使用at 来访问索引值0和4之间的行以及列point和assists。

#try to select rows between index values 0 and 4 and columns 'points' and 'assists'
df.at[0:4, ['points', 'assists']] 

TypeError: unhashable type: 'list'

我们会收到一个错误,因为at函数不能接受多行或多列作为输入参数。

总结

当你想在pandas DataFrame中只访问一个值时,locat函数都能正常工作。

然而,当你想访问一组行和列时,只有loc函数能够做到。

相关内容: Pandas loc vs. iloc:有什么区别?

其他资源

下面的教程解释了如何在pandas中执行其他常见操作:

如何使用Pandas loc按多个条件选择行
如何在Pandas中根据列值选择行
如何在Pandas中按索引选择行