使用方括号或点访问列有什么区别? [英] What is the difference between using squared brackets or dot to access a column?

查看:38
本文介绍了使用方括号或点访问列有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下两种情况下:

import pandas

d = {'col1': 2, 'col2': 2.5}
df = pandas.DataFrame(data=d, index=[0])

print(df['col2'])
print(df.col2)

两种方法都可以对列进行索引并产生相同的结果,那么它们之间有什么区别吗?

Both methods can be used to index on a column and yield the same result, so is there any difference between them?

推荐答案

点符号",即 df.col2属性访问,为了方便而公开.

The "dot notation", i.e. df.col2 is the attribute access that's exposed as a convenience.

您可以直接作为属性访问系列上的索引、DataFrame 上的列和面板上的项目:

You may access an index on a Series, column on a DataFrame, and an item on a Panel directly as an attribute:

df['col2'] 做同样的事情:它返回列的 pd.Series.

df['col2'] does the same: it returns a pd.Series of the column.

关于属性访问的一些注意事项:

A few caveats about attribute access:

  • 你不能添加一个列(df.new_col = x 不起作用,更糟糕的是:它会悄悄地实际创建一个新属性而不是一个列 - 想想猴子-在这里打补丁)
  • 如果列名中有空格或列名是整数,则此方法无效.
  • you cannot add a column (df.new_col = x won't work, worse: it will silently actually create a new attribute rather than a column - think monkey-patching here)
  • it won't work if you have spaces in the column name or if the column name is an integer.

这篇关于使用方括号或点访问列有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆