Skip to main content
 首页 » 编程设计

python之关于 Pandas 数据帧索引的不变性

2025年05月04日15zhengyun_ustc

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

我是不是漏掉了什么?

这是我尝试过的:

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 

请您参考如下方法:

请注意,罪魁祸首在 __setitem__ 中Index 类的方法:

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

当您尝试设置索引的元素时,将引发此 TypeError。但是,这并没有说明重新分配索引。

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

frame.index = index  # Line 3016 

意思是,您可以随时重新分配索引。


一个类似的例子应该有所帮助。假设您了解字符串的不变性。

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 视为有序的卡住集。