我有以下代码。
s2 = pd.Series([100,"PYTHON","Soochow","Qiwsir"],
index=["mark","title","university","name"])
s2.mark = "102"
s2.price = "100"
当我打印
s2
时,我可以看到标记的值已更改,并且没有价格;但是通过打印s2.price
,我可以获得结果。为什么price
未打印出来?我有以下代码。
s2 = pd.Series([100,"PYTHON","Soochow","Qiwsir"],
index=["mark","title","university","name"])
s2.mark = "102"
s2.price = "100"
s2
时,我可以看到标记的值已更改,并且没有价格;但是通过打印s2.price
,我可以获得结果。为什么price
未打印出来?你把属性和系列索引搞混了。
语法s2.xyz = 100
首先在系列索引中查找xyz
,如果存在则覆盖它。
如果不存在,则向系列添加新的属性。
如何添加属性
if 'price' not in s2:
s2.price = 100
在添加属性时,不应与索引冲突;由于具有类似语法的访问权限,这样做可能会带来麻烦。
如何向系列中添加元素
要向具有索引的系列中添加元素,请使用pd.Series.loc
:
s2.loc['price'] = 100
如何区分
运行 s2.__dict__
。你会发现:
{'_data': SingleBlockManager
Items: Index(['mark', 'title', 'university', 'name'], dtype='object')
ObjectBlock: 4 dtype: object,
'_index': Index(['mark', 'title', 'university', 'name'], dtype='object'),
'_item_cache': {},
'_name': None,
'_subtyp': 'series',
'is_copy': None,
'price': '100'}
很明显,price
已被添加为一个属性而不是一个索引。