As pointed out by several answers, the problem isn't that you have duplicate values in your index (the error message certainly does not help here), but rather that you have duplicates of (index, column)
. Some answers are suggesting that you just drop these duplicates but I'd be careful about doing so - in my experience this is rarely the correct choice. More often than not, you probably want to aggregate your data somehow, and then pivot.
I'm pulling some examples and quotes from this blog post, which I suggest you read for more details, below.
Given data like this:
df = pd.DataFrame([
['a', 'x', 1],
['a', 'x', 2],
['b', 'x', 3],
['b', 'y', 4]
], columns=['g1', 'g2', 'value'])
which prints like this:
>>> print(df)
g1 g2 value
0 a x 1
1 a x 2
2 b x 3
3 b y 4
we get a ValueError
when attempting to pivot with g1
as the index and g2
as the columns:
>>> df.pivot(index='g1', columns='g2', values='value')
...
ValueError: Index contains duplicate entries, cannot reshape
Notice that rows 0 and 1 have the same values for g1
and g2
: (a, x)
. So when pandas creates your pivoted dataframe, for the a
index, g1
column, how do pick just one value: 1 or 2? The answer is... we can't! This is why dropping duplicates works, but it may not be you want, since you're losing potentially useful data. So what can we do instead?
Solution 1: Aggregate
There won't always be an aggregate function that makes sense for your use case, but if there is, there are several ways to accomplish this.
df.pivot_table(index='g1', columns='g2', values='value', aggfunc='sum')
df_agg = df.groupby(by=['g1', 'g2']).value.sum().reset_index()
df_agg.pivot(index='g1', columns='g2', values='value')
df.groupby(by=['g1', 'g2']).value.sum().unstack()
All of these yield the same result:
g2 x y
g1
a 3.0 NaN
b 3.0 4.0
But what if you don't need the sum? Maybe comma separated values are useful in your case?
df.pivot_table(
index='g1',
columns='g2',
values='value',
aggfunc=lambda x: ','.join(x.astype('str'))
)
# we need to convert to strings before we can join
to get:
g2 x y
g1
a 1,2 NaN
b 3 4
or you can use list
as your aggfunc
:
pv = df.pivot_table(index='g1', columns='g2', values='value', aggfunc=list)
and then we can explode!
>>> pv.explode('x').explode('y')
g2 x y
g1
a 1 NaN
a 2 NaN
b 3 4
Solution 2: Give yourself another key
This is based on this answer
>>> df['key'] = df.groupby(['g1', 'g2']).cumcount()
>>> df
g1 g2 value key
0 a x 1 0
1 a x 2 1
2 b x 3 0
3 b y 4 0
and now we can pivot with a composite index:
>>> df.pivot(index=['key', 'g1'], columns='g2', values='value').reset_index().drop(columns='key')
g2 g1 x y
0 a 1.0 NaN
1 b 3.0 4.0
2 a 2.0 NaN
This is almost the same result as the exploded example above, just a set_index('g1')
away.
Hope this helps! I hit this problem quite often and usually forget all of this..