【发布时间】:2019-03-19 02:00:30
【问题描述】:
我正在使用下面的代码,但在旋转 DataFrame 后出现错误:
数据框:
name day value time
0 MAC000002 2012-12-16 0.147 09:30:00
1 MAC000002 2012-12-16 0.110 10:00:00
2 MAC000002 2012-12-16 0.736 10:30:00
3 MAC000002 2012-12-16 0.404 11:00:00
4 MAC000003 2012-12-16 0.845 00:30:00
读入数据并进行数据透视
ddf = dd.read_csv('data.csv')
#I added this but didnt fix the error below
ddf.index.name = 'index'
#dask requires string as category type
ddf['name'] = ddf['name'].astype('category')
ddf['name'] =ddf['name'].cat.as_known()
#pivot the table
df = ddf.pivot_table(columns='name', values='value', index='index')
df.head()
#KeyError: 'index'
预期结果(带或不带索引) - 将行转为列而不进行任何值修改:
MAC000002 MAC000003 ...
0.147 0.845
0.110 ...
0.736 ...
0.404 ...
知道为什么我会收到 KeyError 'index' 以及如何克服这个问题吗?
【问题讨论】:
-
哪一行会产生错误?
-
您想要的结果究竟是什么?
-
@Cezary.Sz KeyError Traceback (最近一次调用最后一次)
in () ----> 1 df.head() -
@jpp 我在问题中添加了预期结果
-
不要命名索引尝试
ddf.reset_index(),这样你就有一个名为“索引”的列。
标签: python pandas dataframe pivot-table dask