1

[1]: https://eksiup.com/p/og291345b64f #data.df

With R:

spread(weather3,measure,value)

How do we do the same operation in python? I've tried. but I get an error.

weather3.pivot(index=["year","month","day"], columns="measure", values="value")

gives

ValueError Traceback (most recent call last)
<ipython-input-127-95fb6f73325f> in <module>
----> 1 df1.pivot(index=["year","month","day"], columns="measure", values="value")
D:\Program Files\Anaconda3\lib\site-packages\pandas\core\frame.py in pivot(self, index, columns, values)
   5917         from pandas.core.reshape.pivot import pivot
   5918 
-> 5919         return pivot(self, index=index, columns=columns, values=values)
   5920 
   5921     _shared_docs[
D:\Program Files\Anaconda3\lib\site-packages\pandas\core\reshape\pivot.py in pivot(data, index, columns, values)
    427             )
    428         else:
--> 429             indexed = data._constructor_sliced(data[values].values, index=index)
    430     return indexed.unstack(columns)
    431 
D:\Program Files\Anaconda3\lib\site-packages\pandas\core\series.py in __init__(self, data, index, dtype, name, copy, fastpath)
    297                         raise ValueError(
    298                             "Length of passed values is {val}, "
--> 299                             "index implies {ind}".format(val=len(data), ind=len(index))
    300                         )
    301                 except TypeError:

ValueError: Length of passed values is 8866, index implies 3
  • 1
    Please don't link images of code. Paste the code in the question instead. See [why you sholdn't post images of code](https://meta.stackoverflow.com/a/285557/389289) (same goes for image of short textual data) – zvone Nov 11 '19 at 19:53
  • Try not using a list input for parameters columns and values `weather3.pivot(index=["year","month","day"], columns="measure", values="value")` – Suraj Motaparthy Nov 11 '19 at 19:59
  • I've tried. Now I get this error. (Length of passed values is 8866, index implies 3) – databenderr Nov 11 '19 at 20:19
  • https://stackoverflow.com/questions/36537945/reshape-wide-to-long-in-pandas – M-- Nov 11 '19 at 20:32
  • This function("melt") corresponds to the 'gather' function.I want the corresponds of spread. – databenderr Nov 11 '19 at 20:38
  • Then this one: https://stackoverflow.com/questions/22798934/pandas-long-to-wide-reshape-by-two-variables – M-- Nov 11 '19 at 21:27

1 Answers1

2

problem solved.

weather.pivot_table(weather, values='value', index=['year',"month","day"],
              columns='measure', aggfunc=sum)
weather2=weather.reset_index()