Python pivot valueerror index contains duplicate entries cannot reshape

ValueError: Index contains duplicate entries, cannot reshape

This is a pretty common error you might encounter when you try to pivot data frame in pandas. Pivoting data frame on the other hand is a very common operation when doing data analysis; Pivoting converts data from long format to wide format. Let’s first try to reproduce that error.

Let’s say we have a data frame as follows:

df = pd.DataFrame([ ['a', 'x', 1], ['a', 'x', 2], ['b', 'x', 3], ['b', 'y', 4] ], columns=['g1', 'g2', 'value']) print(df) # g1 g2 value #0 a x 1 #1 a x 2 #2 b x 3 #3 b y 4

And we want to pivot it to wide format, something like the following:

Now pandas has the built in pivot function we can use, let’s try that:

df.pivot(index='g1', columns='g2', values='value')

But we get the error: ValueError: Index contains duplicate entries, cannot reshape. What happened?

This error has nothing to do with our function call, but is in fact a data issue.

Remember that pivot is a dead simple data reshape and it doesn’t do any aggregation. So when we are trying to pivot our data frame, our index column (which goes to the index) and columns column (which goes to the header) combination must not have any duplicates, otherwise, pivot doesn’t know how to reshape your data.

Читайте также:  Custom php in wordpress post

In our simple case above, notice the first row and second row both have (‘a’, ‘x’) combination for g1 and g2 columns, this violates the assumption made by the pivot function:

# g1 g2 value #0 a x 1 #1 a x 2 #2 b x 3 #3 b y 4

1). pivot_table : pivot_table has similar syntax as pivot , but it also allows you to specify an aggregate function via the aggfunc parameter, which aggregates duplicated column combination for you before hand.

df.pivot_table(index='g1', columns='g2', values='value', aggfunc='sum') #g2 x y #g1 #a 3.0 NaN #b 3.0 4.0

2). Pre-aggregate your data yourself and then do pivot , in the following example, we first sum value column by g1 and g2 , reset the grouped index, and then do the pivot . Notice the group operation eliminate the duplicated g1 / g2 column combination:

df_agg = df.groupby(by=['g1', 'g2']).value.sum().reset_index() df_agg # g1 g2 value #0 a x 3 #1 b x 3 #2 b y 4 df_agg.pivot(index='g1', columns='g2', values='value') #g2 x y #g1 #a 3.0 NaN #b 3.0 4.0

Extra credits: you can also use unstack instead of pivot :

df.groupby(by=['g1', 'g2']).value.sum().unstack() #g2 x y #g1 #a 3.0 NaN #b 3.0 4.0

Источник

Как исправить: ValueError: Индекс содержит повторяющиеся записи, не может изменить форму

Одна ошибка, с которой вы можете столкнуться при использовании pandas:

ValueError : Index contains duplicate entries, cannot reshape 

Эта ошибка обычно возникает, когда вы пытаетесь изменить форму DataFrames pandas с помощью функции pivot () , но в результирующем DataFrame есть несколько значений, которые имеют одни и те же значения индекса.

В следующем примере показано, как исправить эту ошибку на практике.

Как воспроизвести ошибку

Предположим, у нас есть следующие Pandas DataFrame:

import pandas as pd #create DataFrame df = pd.DataFrame() #view DataFrame df team position points 0 A G 5 1 A G 7 2 A F 7 3 A F 9 4 B G 4 5 B G 9 6 B F 9 7 B F 12 

Теперь предположим, что мы пытаемся повернуть DataFrame, используя команду в качестве строк и позицию в качестве столбцов:

#attempt to reshape DataFrame df.pivot(index='team', columns='position', values='points') ValueError : Index contains duplicate entries, cannot reshape 

Мы получаем сообщение об ошибке, потому что в DataFrame есть несколько строк с одинаковыми значениями для команды и позиции .

Таким образом, когда мы пытаемся изменить форму DataFrame, pandas не знает, какое значение точек отображать в каждой ячейке в результирующем DataFrame.

Как исправить ошибку

Чтобы исправить эту ошибку, мы можем использовать функцию pivot_table() с определенным аргументом aggfunc для агрегирования значений данных определенным образом.

Например, мы можем использовать pivot_table() для создания нового DataFrame, который использует команду в качестве строк, позицию в качестве столбцов и сумму значений точек в ячейках DataFrame:

df.pivot_table (index='team', columns='position', values='points', aggfunc='sum') position F G team A 16 12 B 21 13 

Обратите внимание, что на этот раз мы не получаем ошибку.

Значения в DataFrame показывают сумму очков для каждой комбинации команды и позиции .

Обратите внимание, что мы могли бы также использовать другое значение для aggfunc , например, среднее значение:

df.pivot_table (index='team', columns='position', values='points', aggfunc='mean') position F G team A 8.0 6.0 B 10.5 6.5 

Используя аргумент aggfunc в функции pivot_table() , мы можем избежать ошибок.

Примечание. Полную документацию по функции pivot_table() можно найти здесь .

Дополнительные ресурсы

В следующих руководствах объясняется, как исправить другие распространенные ошибки в Python:

Источник

Pivot: ValueError: Index contains duplicate entries, cannot reshape [duplicate]

enter image description here

I want to plot a heatmap between hashtags and username from the given final table after cleaning and pre-processing. Getting the following error. I have pasted the full error which I’m getting I searched on similar StackOverflow errors but was unable to get the correct result. final_sns = final.pivot(«hashtags», «username») ax = sns.heatmap(final_sns)

ValueError Traceback (most recent call last) in () ----> 1 final_sns = final.pivot("hashtags", "username") 2 ax = sns.heatmap(final_sns) c:\users\apex_predator\appdata\local\programs\python\python36\lib\site-packages\pandas\core\frame.py in pivot(self, index, columns, values) 5192 """ 5193 from pandas.core.reshape.reshape import pivot -> 5194 return pivot(self, index=index, columns=columns, values=values) 5195 5196 _shared_docs['pivot_table'] = """ c:\users\apex_predator\appdata\local\programs\python\python36\lib\site-packages\pandas\core\reshape\reshape.py in pivot(self, index, columns, values) 413 indexed = self._constructor_sliced(self[values].values, 414 index=index) --> 415 return indexed.unstack(columns) 416 417 c:\users\apex_predator\appdata\local\programs\python\python36\lib\site-packages\pandas\core\frame.py in unstack(self, level, fill_value) 5532 """ 5533 from pandas.core.reshape.reshape import unstack -> 5534 return unstack(self, level, fill_value) 5535 5536 _shared_docs['melt'] = (""" c:\users\apex_predator\appdata\local\programs\python\python36\lib\site-packages\pandas\core\reshape\reshape.py in unstack(obj, level, fill_value) 493 if isinstance(obj, DataFrame): 494 if isinstance(obj.index, MultiIndex): --> 495 return _unstack_frame(obj, level, fill_value=fill_value) 496 else: 497 return obj.T.stack(dropna=False) c:\users\apex_predator\appdata\local\programs\python\python36\lib\site-packages\pandas\core\reshape\reshape.py in _unstack_frame(obj, level, fill_value) 507 unstacker = partial(_Unstacker, index=obj.index, 508 level=level, fill_value=fill_value) --> 509 blocks = obj._data.unstack(unstacker) 510 return obj._constructor(blocks) 511 else: c:\users\apex_predator\appdata\local\programs\python\python36\lib\site-packages\pandas\core\internals.py in unstack(self, unstacker_func) 4608 unstacked : BlockManager 4609 """ -> 4610 dummy = unstacker_func(np.empty((0, 0)), value_columns=self.items) 4611 new_columns = dummy.get_new_columns() 4612 new_index = dummy.get_new_index() c:\users\apex_predator\appdata\local\programs\python\python36\lib\site-packages\pandas\core\reshape\reshape.py in __init__(self, values, index, level, value_columns, fill_value, constructor) 135 136 self._make_sorted_values_labels() --> 137 self._make_selectors() 138 139 def _make_sorted_values_labels(self): c:\users\apex_predator\appdata\local\programs\python\python36\lib\site-packages\pandas\core\reshape\reshape.py in _make_selectors(self) 173 174 if mask.sum() < len(self.index): -->175 raise ValueError('Index contains duplicate entries, ' 176 'cannot reshape') 177 ValueError: Index contains duplicate entries, cannot reshape 

Источник

Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape

What version of pandas are you using? Could you give a small example DataFrame which demonstrates this issue (so we can just run your code and see if we get the same result)?

@AndyHayden I am using pandas 0.15.2. I will try to create a dataframe that reproduces the result, but so far, I have been unable to do so.

This is a very old question, however my two cents.. I was getting this error and while checking the data I found there are duplicates data in my excel cell. I was trying to break multiple rows in a cell to individual rows. Once I remove duplicates, this error is not anymore

3 Answers 3

Here’s an example DataFrame which show this, it has duplicate values with the same index. The question is, do you want to aggregate these or keep them as multiple rows?

In [11]: df Out[11]: 0 1 2 3 0 1 2 a 16.86 1 1 2 a 17.18 2 1 4 a 17.03 3 2 5 b 17.28 In [12]: df.pivot_table(values=3, index=[0, 1], columns=2, aggfunc='mean') # desired? Out[12]: 2 a b 0 1 1 2 17.02 NaN 4 17.03 NaN 2 5 NaN 17.28 In [13]: df1 = df.set_index([0, 1, 2]) In [14]: df1 Out[14]: 3 0 1 2 1 2 a 16.86 a 17.18 4 a 17.03 2 5 b 17.28 In [15]: df1.unstack(2) ValueError: Index contains duplicate entries, cannot reshape 

One solution is to reset_index (and get back to df ) and use pivot_table .

In [16]: df1.reset_index().pivot_table(values=3, index=[0, 1], columns=2, aggfunc='mean') Out[16]: 2 a b 0 1 1 2 17.02 NaN 4 17.03 NaN 2 5 NaN 17.28 

Another option (if you don’t want to aggregate) is to append a dummy level, unstack it, then drop the dummy level.

Источник

Оцените статью