对于Pandas DataFrame,使用方括号或点访问列之间有什么区别? [英] For Pandas DataFrame, what's the difference between using squared brackets or dot to access a column?

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

问题描述

即:

import pandas

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

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

输出是相同的.

此答案适用于这种情况吗?

Does this answer apply to this case?

在Python中使用方括号和点表示法?

推荐答案

点符号",即df.col2

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

您可以直接作为属性访问系列"上的索引,数据框"上的列以及面板"上的项目:

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.

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

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