Python DataFrame属性和列之间的区别是什么 在[66]中:数据 出[66]: col1 col2标签 01.0 a c 1 2.0 b d 23.0CE 30.0华氏度 4.0 e 0 5.0 f 0 In[67]:data.label 出[67]: 0摄氏度 一维 2楠 3楼 4楠 5南 名称:col2,数据类型:object 在[68]中:数据['标签'] 出[68]: 0摄氏度 一维 2e 3楼 4 0 5 0 名称:标签,数据类型:对象

Python DataFrame属性和列之间的区别是什么 在[66]中:数据 出[66]: col1 col2标签 01.0 a c 1 2.0 b d 23.0CE 30.0华氏度 4.0 e 0 5.0 f 0 In[67]:data.label 出[67]: 0摄氏度 一维 2楠 3楼 4楠 5南 名称:col2,数据类型:object 在[68]中:数据['标签'] 出[68]: 0摄氏度 一维 2e 3楼 4 0 5 0 名称:标签,数据类型:对象,python,pandas,dataframe,Python,Pandas,Dataframe,为什么data.label和data['label']显示不同的结果?我注意到的最大区别是赋值 In [66]: data Out[66]: col1 col2 label 0 1.0 a c 1 2.0 b d 2 3.0 c e 3 0.0 d f 4 4.0 e 0 5 5.0 f 0 In [67]: data.label Out[67]: 0 c 1

为什么data.label和data['label']显示不同的结果?

我注意到的最大区别是赋值

In [66]: data Out[66]: col1 col2 label 0 1.0 a c 1 2.0 b d 2 3.0 c e 3 0.0 d f 4 4.0 e 0 5 5.0 f 0 In [67]: data.label Out[67]: 0 c 1 d 2 NaN 3 f 4 NaN 5 NaN Name: col2, dtype: object In [68]: data['label'] Out[68]: 0 c 1 d 2 e 3 f 4 0 5 0 Name: label, dtype: object 给出:
UserWarning:Pandas不允许通过新属性名创建列

但是,也有与此相关的文档:

其中包含以下可能与您的问题有关的警告:

import random
import pandas as pd

s = "SummerCrime|WinterCrime".split("|")
j = {x: [random.choice(["ASB", "Violence", "Theft", "Public Order", "Drugs"]) for j in range(300)] for x in s}
df = pd.DataFrame(j)
df.FallCrime = [random.choice(["ASB", "Violence", "Theft", "Public Order", "Drugs"]) for j in range(300)]
他们接着说:

- You can use this 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. 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.

(所以你可能在没有意识到的情况下做了这件事)

这两者之间的区别与作业有关。使用
data.label
无法将值分配给列

data.label用于访问属性,data[“label”]用于分配值

此外,如果列名中有空格,例如
df['label name']
,则在使用
data.label name
时,会出现错误


有关更多信息,请参见此

,您应该从外部来源(如官方文档)中封锁报价。也许把你的答案写在标记的副本上而不是这里。
You can use attribute access to modify an existing element of a Series or column of a
DataFrame, but be careful; if you try to use attribute access to create a new column,
it creates a new attribute rather than a new column.
**In 0.21.0 and later, this will raise a UserWarning**