python透视表-添加另一列

python透视表-添加另一列,python,sql,pandas,dataframe,pivot-table,Python,Sql,Pandas,Dataframe,Pivot Table,我们希望使用SQL Server创建一个透视表,还希望计算过去两天的增长百分比 下面是使用SQL Server的pivot表的代码 data=pd.read_sql_query("select CONVERT(varchar,created_on,111) as Date,service_name as TFN,isnull(count(*),0) MC_Count from tablename with(nolock) where created_on>=cast(getdate()-1

我们希望使用SQL Server创建一个透视表,还希望计算过去两天的增长百分比

下面是使用SQL Server的pivot表的代码

data=pd.read_sql_query("select CONVERT(varchar,created_on,111) as Date,service_name as TFN,isnull(count(*),0) MC_Count from tablename with(nolock) where created_on>=cast(getdate()-1 as date) and user_Id='xxx' group by CONVERT(varchar,created_on,111),service_name",con)

P=pd.pivot_table(data,index="TFN",columns="Date",values=["MC_Count"],aggfunc={"MC_Count":np.sum})
我想添加另一个百分比增加的列,但我不知道如何添加

格式:


提前感谢

您可以通过位置选择列,通过
100
进行减法、除法和倍数选择:

P['growth%'] = ((P.iloc[:, -1] -  P.iloc[:, -2]) / P.iloc[:, -2]) * 100
print (P)
         15-Jul-18  16-Jul-18  18-Jul-18  growth%
1800XXX        789        800       1009   26.125
18001XX        890        900        900    0.000

如果你想添加一个名为“a”的数组,只需创建一个数据[“new_column”]=a如果你想创建一个空列,只需创建一个数据。插入(loc=4,column=“new_column,value=None)你是否在寻找类似于
P['last_two_days_growth%]=(P['18-Jul-18']-P['15-Jul-18'])/P['15-Jul-18']*100