当我在 pandas 系列中这样做时,价值在哪里? [英] Where is the value when I do this in pandas Series
问题描述
我有以下代码.
s2 = pd.Series([100,"PYTHON","Soochow","Qiwsir"],
index=["mark","title","university","name"])
s2.mark = "102"
s2.price = "100"
当我打印s2
时,可以看到标记的值已更改并且没有价格;但是我可以通过打印s2.price
得到结果.为什么不打印price
?
When I print s2
, I can see the value of mark was changed and there is no price; but I can get result by printing s2.price
. Why is the price
not printed?
推荐答案
您正在将属性与系列索引混淆.
You are confusing attributes with series indices.
语法s2.xyz = 100
首先在系列 index 中查找xyz
,如果存在,则将其覆盖.
The syntax s2.xyz = 100
first looks for xyz
in the series index and overwrites it if it exists.
如果不存在,则会在系列中添加新的属性.
If it does not exist, it adds a new attribute to the series.
如何添加属性
if 'price' not in s2:
s2.price = 100
您不应添加与索引冲突的属性;鉴于允许的访问语法相似,这很麻烦.
You should not add attributes which conflict with indices; this is asking for trouble given the similar syntax permitted for access.
如何向系列添加元素
为了将带有索引的元素添加到系列中,请使用pd.Series.loc
:
In order to add an element to the series with an index, use 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
是作为属性添加的,而不是作为 index 添加的.
It is clear that price
has been added as an attribute, not as an index.
这篇关于当我在 pandas 系列中这样做时,价值在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!