问题描述
例如,我有一个这样的数据框.
For example I have a dataframe like this.
Date Open High Low Close \
0 2009-08-25 20246.789063 20476.250000 20143.509766 20435.240234
Adj Close Volume
0 20435.240234 1531430000
使用属性或显式命名都会给我相同的输出:
Using attribute or explicit naming both give me the same output:
sum(data.Date==data['Date']) == data.shape[0]
True
但是我无法访问以空格命名的列,例如使用df.columnname的"Adj Close",但是可以使用df ['columnname'].
However I cannot access columns that are named with white space, like 'Adj Close' with df.columnname, but can do with df['columnname'].
使用df ['columnname']严格比使用df.columnname好吗?
Is using df['columnname'] strictly better than using df.columnname ?
推荐答案
使用.
作为列访问器很方便.除了名称中有空格以外,还有很多限制.例如,如果您的列的名称与现有数据框属性或方法的名称相同,则您将无法将其与.
一起使用.非穷举列表是mean
,sum
,index
,values
,to_dict
等.您也不能通过.
访问器引用带有数字标题的列.
Using .
as a column accessor is a convenience. There are many limitations beyond having spaces in the name. For example, if your column is named the same as an existing dataframe attribute or method, you won't be able to use it with a .
. A non-exhaustive list is mean
, sum
, index
, values
, to_dict
, etc. You also cannot reference columns with numeric headers via the .
accessor.
所以,是的,['col']
严格优于.col
,因为它更加一致和可靠.
So, yes, ['col']
is strictly better than .col
because it is more consistent and reliable.
这篇关于正确的方法来访问 pandas 数据框的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!