[英]'tuple' object does not support item assignment - DataFrame
I have a dictionary d
of data frames, where the keys are the names and the values are the actual data frames.我有一个数据框字典d
,其中键是名称,值是实际数据框。 I have a function that normalizes some of the data frame and spits out a plot, with the title.我有一个 function 规范化一些数据帧并吐出一个 plot,标题。 The function takes in a tuple from d.items()
(as the parameter df
) so the first (0th) element is the name and the next is the data frame. function 从d.items()
中获取一个元组(作为参数df
),因此第一个(第 0 个)元素是名称,下一个是数据帧。
I have to do some manipulations on the data frame in the function, and I do so using df[1]
without any issues.我必须对 function 中的数据框进行一些操作,并且我使用df[1]
这样做没有任何问题。 However, one line is df[1] = df[1].round(2)
and this throws the error 'tuple' object does not support item assignment
.但是,一行是df[1] = df[1].round(2)
,这会引发错误'tuple' object does not support item assignment
。 I have verified that df[1]
is a data frame by printing out its type write before this line.我已经通过在此行之前打印出它的类型 write 来验证df[1]
是一个数据帧。 Why doesn't this work?为什么这不起作用? It's not a tuple.它不是一个元组。
That's because your variable is a tuple and you can't assign to a tuple.那是因为你的变量是一个元组,你不能分配给一个元组。 Tuples are immutable.元组是不可变的。 My understanding of your question:我对你的问题的理解:
from pandas import DataFrame
d = {'mydf' : DataFrame({'c1':(1,2),'c2':(4,5)}) } #A dictionary of DFs.
i = list(d.items())[0] #The first item from .items()
i[1] = i[1].round(2) #ERROR
Notice that "i" is a tuple, because that is what.items() returns (tuples).请注意,“i”是一个元组,因为那是.items() 返回的内容(元组)。 You can't save to i, even if what you are overwriting is something that is mutable.即使您要覆盖的内容是可变的,您也无法保存到 i 中。 I know that this sounds strange, because you can do things like this:我知道这听起来很奇怪,因为你可以这样做:
x = (7,[1,2,3])
x[1].append(4)
print(x)
The reason this works is complicated.这样做的原因很复杂。 Essentially the tuples above are storing the pointers to the information within the tuples (not the data themselves).本质上,上面的元组存储了指向元组内信息的指针(而不是数据本身)。 Hence, if you access a tuple's item (like x[1]), then python takes you to that pointers item (in my case a list) and allows you to run append on it, because the list is mutable.因此,如果您访问元组的项目(如 x[1]),则 python 会将您带到该指针项目(在我的情况下为列表)并允许您在其上运行 append,因为该列表是可变的。 In your case, you are not trying to access the i[1] all by itself, you are trying to overwrite the i[1] entry in the tuple.在您的情况下,您不是试图单独访问 i[1] ,而是试图覆盖元组中的 i[1] 条目。 Hope this makes sense.希望这是有道理的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.