Reputation: 613
I am trying to pivot a dataframe which is like below.
twt=DataFrame(time_weekday_tip.groupby(["weekday", "time_hour"])["Tip_amount"].mean())
twt.reset_index()
print (twt.columns.tolist())
twt.columns = twt.columns.str.strip()
twt.pivot(index='time_hour', columns='weekday', values='Tip_amount')
But i get below error. Please advise.
pandas/src/hashtable_class_helper.pxi in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:13742)()
pandas/src/hashtable_class_helper.pxi in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:13696)()
KeyError: 'time_hour'
Upvotes: 2
Views: 4373
Reputation: 862841
It seems some whitespace space in columns name, check it by:
print (twt.columns.tolist())
For remove it use strip
:
twt.columns = twt.columns.str.strip()
Also better is use parameter values
in pivot
:
twt.pivot(index='time_hour', columns='weekday', values='Tip_amount')
EDIT:
I think only unstack
is necessary and remove another code:
twt = time_weekday_tip.groupby(["weekday", "time_hour"])["Tip_amount"].mean().unstack(0)
EDIT2:
Another solution is add reset_index
to the end:
twt= time_weekday_tip.groupby(["weekday", "time_hour"])["Tip_amount"].mean().reset_index()
twt.pivot(index='time_hour', columns='weekday', values='Tip_amount')
twt= time_weekday_tip.groupby(["weekday", "time_hour"], as_index=False)["Tip_amount"].mean()
twt.pivot(index='time_hour', columns='weekday', values='Tip_amount')
Upvotes: 2