如何将计算字段添加到数据透视表

时间:2019-05-25 03:30:48

标签: python pandas

我有一个数据集,其中有2列为customer_id和use_time。

我要创建一个数据透视表,其中包含:

index=use_time, 
value=count(customer_id)

然后通过获取count(customer_id)/ use_time将一列添加为数据透视表名称为count1

这是我写的代码:

import pandas as pd
import numpy as np
df=pd.read_csv("C:\\Users\\n.nguyen.2\\Documents\\Lovefood voucher.csv")
table=pd.pivot_table(df,index="use_time",values="customer_id",aggfunc= "count")
table['count1']=table['customer_id']/table['use_time']
writer = pd.ExcelWriter("C:\\Users\\n.nguyen.2\\Documents\\Lovefood voucher pivot.xlsx")
table.to_excel(writer, 'Sheet1')
writer.save()

错误消息是这样的:

Traceback (most recent call last):

  File "<ipython-input-127-1fc32ada5ee2>", line 6, in <module>
    table['count1']=table['customer_id']/table['use_time']

  File "C:\Users\n.nguyen.2\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py", line 2927, in __getitem__
    indexer = self.columns.get_loc(key)

  File "C:\Users\n.nguyen.2\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 2659, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))

  File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc

  File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc

  File "pandas/_libs/hashtable_class_helper.pxi", line 1601, in pandas._libs.hashtable.PyObjectHashTable.get_item

  File "pandas/_libs/hashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: 'use_time'

能请你帮忙吗?谢谢!

Data set Output

0 个答案:

没有答案