[1]:https://eksiup.com/p/og291345b64f#data.df
使用R:
spread(weather3,measure,value)
我们如何在python中执行相同的操作?我试过了。但出现错误。
weather3.pivot(index=["year","month","day"], columns="measure", values="value")
给予
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
答案 0 :(得分:2)
问题解决了。
weather.pivot_table(weather, values='value', index=['year',"month","day"],
columns='measure', aggfunc=sum)
weather2=weather.reset_index()