简体   繁体   中英

'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. I have a function that normalizes some of the data frame and spits out a plot, with the title. 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.

I have to do some manipulations on the data frame in the function, and I do so using df[1] without any issues. However, one line is df[1] = df[1].round(2) and this throws the error '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. 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). You can't save to i, even if what you are overwriting is something that is mutable. 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. 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. Hope this makes sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM