Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

python - Pandas pivot warning about repeated entries on index

On Pandas documentation of the pivot method, we have:

Examples
--------
>>> df
    foo   bar  baz
0   one   A    1.
1   one   B    2.
2   one   C    3.
3   two   A    4.
4   two   B    5.
5   two   C    6.

>>> df.pivot('foo', 'bar', 'baz')
     A   B   C
one  1   2   3
two  4   5   6

My DataFrame is structured like this:

   name   id     x
----------------------
0  john   1      0
1  john   2      0
2  mike   1      1
3  mike   2      0

And I want something like this:

      1    2   # (this is the id as columns)
----------------------
mike  0    0   # (and this is the 'x' as values)
john  1    0

But when I run the pivot method, it is saying:

*** ReshapeError: Index contains duplicate entries, cannot reshape

Which doesn't makes sense, even in example there are repeated entries on the foo column. I'm using the name column as the index of the pivot, the first argument of the pivot method call.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As far as I can tell with updates to pandas, you have to use pivot_table() instead of pivot().

pandas.pivot_table(df,values='count',index='site_id',columns='week')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...