Skip to main content
 首页 » 编程设计

python之dataframes 通过 [] 和 .(attribute) 选择数据

2025年02月15日8del

我发现我在理解什么时候应该使用 df[data] 或 df.data 从 dataframe(df) 访问数据时遇到问题。 我主要使用 [] 方法来创建新列,但我也可以使用 df[] 和 df.data 访问数据,但有什么区别,我该如何做更好地掌握这两种选择数据的方式?什么时候应该使用一个而不是另一个?

请您参考如下方法:

如果我理解Docs正确地说,它们几乎是等价的,除了这些情况:

  • You can use [the .] access only if the index element is a valid python identifier, e.g. s.1 is not allowed.
  • The attribute will not be available if it conflicts with an existing method name, e.g. s.min is not allowed.
  • Similarly, the attribute will not be available if it conflicts with any of the following list: index, major_axis, minor_axis, items, labels.
  • In any of these cases, standard indexing will still work, e.g. s['1'], s['min'], and s['index'] will access the corresponding element or column.

然而,虽然

indexing operators [] and attribute operator . provide quick and easy access to pandas data structures across a wide range of use cases [...]

在生产中你真的应该使用优化的 panda 数据访问方法,例如 .loc、.iloc 和 .ix,因为

[...] since the type of the data to be accessed isn’t known in advance, directly using standard operators has some optimization limits. For production code, we recommended that you take advantage of the optimized pandas data access methods.