【问题标题】:Where is the value when I do this in pandas Series当我在熊猫系列中这样做时,价值在哪里
【发布时间】:2018-04-10 08:21:54
【问题描述】:

我有以下代码。

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

s2.mark = "102"

s2.price = "100"

当我打印 s2 时,我可以看到标记的值发生了变化,并且没有价格;但我可以通过打印s2.price 得到结果。为什么price 没有打印出来?

【问题讨论】:

标签: python pandas series


【解决方案1】:

您将属性与系列索引混淆了。

语法s2.xyz = 100首先在序列index中查找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 已添加为属性,而不是索引

【讨论】:

    猜你喜欢
    • 2021-07-06
    • 2019-08-03
    • 2016-10-25
    • 1970-01-01
    • 2018-05-26
    • 2022-10-24
    • 1970-01-01
    • 2017-07-30
    相关资源
    最近更新 更多