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

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

问题描述

在以下两种情况下:

import pandas

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

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

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

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

推荐答案

点符号,即 df.col2 是< 为方便起见,提供了一个href = http://pandas-docs.github.io/pandas-docs-travis/indexing.html#attribute-access rel = noreferrer>属性访问。 p>

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


您可以直接作为属性访问Series上的索引,DataFrame上的列和Panel上的项目:

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

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

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天全站免登陆