关于 pandas 数据框索引的不变性 [英] Regarding the immutability of pandas dataframe indexes

查看:32
本文介绍了关于 pandas 数据框索引的不变性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文档中读到,索引对象是不可变的,一旦创建就无法更改.但是我可以在创建后更改值.

I read in the documentation that the index objects are immutable and can not be changed once created. But I can change the values after creation.

我在这里想念东西吗?

这是我尝试过的:

ser = pd.Series([5,0,3,8,4], index=['red','blue','yellow','white','green'])
ser

red       5
blue      0
yellow    3
white     8
green     4
dtype: int64

ser.index = ['red','blue','yellow','white','test']
ser

red       5
blue      0
yellow    3
white     8
test      4
dtype: int64

推荐答案

请注意,罪魁祸首在

Note that the culprit is in the __setitem__ method of the Index class:

def __setitem__(self, key, value):
    raise TypeError("Index does not support mutable operations")

当您尝试设置索引元素时,引发此 TypeError .但是,这与重新分配索引无关.

This TypeError is raised when you try to set an element of the index. However, this says nothing about reassigning the index.

OTOH,如果您考虑 df.set_index 这是一种设置索引的方法,您将看到,最后,它已完成:

OTOH, if you consider df.set_index which is a method to set the index, you'll see that, at the end, this is done:

frame.index = index  # Line 3016

意味着,您可以随时重新分配索引.

Meaning, you may re-assign the index at any time.

一个类似的例子应该会有所帮助.假设,您已经知道了字符串的不变性.

A similar example should help. Assuming, you're aware of the immutability of strings.

string = 'test'

是可能的:

string = 'test2'  # reassignment

但是这个不是:

string[0] = c     # item assignment... mutating the same object! 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-233-27903bb729b1> in <module>()
----> 1 s[0] = c

TypeError: 'str' object does not support item assignment


以类似的方式,可变性!=重新分配. ser.index 的工作与此类似.您可能会认为 index 是有序的Frozenset.


In a similar fashion mutability != reassignment. ser.index works similar to this. You may think of the index as an ordered frozenset.

这篇关于关于 pandas 数据框索引的不变性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆