我在熊猫系列中的价值在哪里?

C.M*_*ing 10 python series pandas

我有以下代码.

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

s2.mark = "102"

s2.price = "100"
Run Code Online (Sandbox Code Playgroud)

当我打印时s2,我可以看到标记的价值已经改变而且没有价格; 但我可以通过打印得到结果s2.price.为什么price不打印?

jpp*_*jpp 10

您将属性与系列索引混淆.

语法s2.xyz = 100首先xyz在系列索引中查找,如果存在则覆盖它.

如果它不存在,则会向该系列添加新属性.

如何添加属性

if 'price' not in s2:
    s2.price = 100
Run Code Online (Sandbox Code Playgroud)

您不应该添加与索引冲突的属性; 鉴于允许访问的类似语法,这是在寻找麻烦.

如何向系列添加元素

要使用索引向元素添加元素,请使用pd.Series.loc:

s2.loc['price'] = 100
Run Code Online (Sandbox Code Playgroud)

如何区分

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'}
Run Code Online (Sandbox Code Playgroud)

很明显,它price已被添加为属性,而不是作为索引.