Python 关于数据帧索引的不变性
我在文档中读到,索引对象是不可变的,一旦创建就不能更改。但我可以在创建后更改值 我是不是遗漏了什么 这就是我所尝试的:Python 关于数据帧索引的不变性,python,pandas,dataframe,immutability,Python,Pandas,Dataframe,Immutability,我在文档中读到,索引对象是不可变的,一旦创建就不能更改。但我可以在创建后更改值 我是不是遗漏了什么 这就是我所尝试的: 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',
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
您可以像以前一样更改对象ser.index
引用,但一旦指定对象,就不能对其进行变异:
>>> import pandas as pd
>>> ser = pd.Series([5,0,3,8,4], index=['red','blue','yellow','white','green'])
>>> ser.index[2] = 'coconut'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/indexes/base.py", line 1404, in __setitem__
raise TypeError("Index does not support mutable operations")
TypeError: Index does not support mutable operations
请注意,罪魁祸首在
索引的方法中
类:
def __setitem__(self, key, value):
raise TypeError("Index does not support mutable operations")
当您尝试设置索引的元素时,会引发此TypeError
。然而,这与重新分配索引无关
frame.index = index # Line 3016
也就是说,您可以随时重新分配索引
类似的例子应该会有所帮助。假设您知道字符串的不变性
string = 'test'
这是可能的:
string = 'test2' # reassignment
但这不是:
string[0]=c#项目分配。。。变异同一个对象!
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在()
---->1s[0]=c
TypeError:“str”对象不支持项分配
以类似的方式可变!=重新分配<代码>序列索引的工作原理与此类似。您可能认为
索引
是一个有序的冻结集 这意味着你不能做ser.index[0]='wack'
这在语义上有点不同,你要做的是用一个全新的索引替换索引,但是你不能像@JohnGalt那样更改单个索引元素,答案已经显示出来了
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