formicaman
formicaman

Reputation: 1357

'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.

Upvotes: 1

Views: 824

Answers (1)

Bobby Ocean
Bobby Ocean

Reputation: 3328

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.

Upvotes: 1

Related Questions