键错误 - 旋转数据帧时

时间:2017-04-21 05:41:43

标签: python pandas numpy dataframe

我正在尝试调整数据框,如下所示。

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')

enter image description here

但我得到以下错误。请指教。

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'

1 个答案:

答案 0 :(得分:1)

列名中似乎有一些空格,请按以下方式检查:

print (twt.columns.tolist())

要删除它,请使用strip

twt.columns = twt.columns.str.strip()

更好的是在pivot中使用参数values

twt.pivot(index='time_hour', columns='weekday', values='Tip_amount')

编辑:

我认为只需要unstack并删除其他代码:

 twt = time_weekday_tip.groupby(["weekday", "time_hour"])["Tip_amount"].mean().unstack(0)

EDIT2:

另一种解决方案是在最后添加reset_index

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')