Where is the value when I do this in pandas Series

社会主义新天地 提交于 2019-12-01 15:18:21

问题


I have the following code.

s2 = pd.Series([100,"PYTHON","Soochow","Qiwsir"],
               index=["mark","title","university","name"])

s2.mark = "102"

s2.price = "100"

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?


回答1:


You are confusing attributes with series indices.

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.

How to add an attribute

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.

How to add an element to series

In order to add an element to the series with an index, use pd.Series.loc:

s2.loc['price'] = 100

How to tell the difference

Run s2.__dict__. You will find:

{'_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'}

It is clear that price has been added as an attribute, not as an index.



来源:https://stackoverflow.com/questions/49748749/where-is-the-value-when-i-do-this-in-pandas-series

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!