Skip to content Skip to sidebar Skip to footer

Valueerror: Too Many Values To Unpack When Using Itertuples() On Pandas Dataframe

I am trying to convert a simple pandas dataframe into a nested JSON file based on the answer I found here: pandas groupby to nested json My grouped dataframe looks like this:

Solution 1:

When using itertuples(), the index is included as part of the tuple, so the for index, value in grouped.itertuples(): doesn't really make sense. In fact, itertuples() uses namedtuple with Index being one of the names.

Consider the following setup:

data = {'A': list('aabbc'), 'B': [0, 1, 0, 1, 0], 'C': list('vwxyz'), 'D': range(5,10)}
df = pd.DataFrame(data).set_index(['A', 'B'])

Yielding the following DataFrame:

     C  D
ABa0  v  51  w  6b0  x  71  y  8
c 0  z  9

Then printing each tuple in df.itertuples() yields:

Pandas(Index=('a', 0), C='v', D=5)
Pandas(Index=('a', 1), C='w', D=6)
Pandas(Index=('b', 0), C='x', D=7)
Pandas(Index=('b', 1), C='y', D=8)
Pandas(Index=('c', 0), C='z', D=9)

So, what you'll probably want to do is something like the code below, with value being replaced by t[1:]:

fortin grouped.itertuples():
    fori, key inenumerate(t.Index):
        ...

If you want to access components of the namedtuple, you can access things positionally, or by name. So, in the case of your DataFrame, t[1] and t.firstname should be equivalent. Just remember that t[0] is the index, so your first column starts at 1.

Solution 2:

As I understand itertuples, it will return a tuple with the first value being the index and the remaining values being all of the columns. You only have for index, value in grouped.itertuples() which means it's trying to unpack all of the columns into a single variable, which won't work. The groupby probably comes into play as well but it should still contain all the values within the result which means you still have too many columns being unpacked.

Post a Comment for "Valueerror: Too Many Values To Unpack When Using Itertuples() On Pandas Dataframe"