索引重置reset_index(inplace=True) 中的inplace=True什么时候添加

inplace=True :是指重置索引的结果是否作用在前面的数据上

 

我们并不能设置df.pivot_table(values='orderamount',index='month',aggfunc=sum) 输出结果的格式,所以在 

df.pivot_table(values='orderamount',index='month',aggfunc=sum) 上重置索引的时候,reset_index()中不能添加inplace=True.


但是变量a,是把 df.pivot_table(values='orderamount',index='month',aggfunc=sum)的结果赋给变量a了,

此时a和 “df.pivot_table(values='orderamount',index='month',aggfunc=sum)” 并没有等价关系,不能说a代表的是

“df.pivot_table(values='orderamount',index='month',aggfunc=sum)” ,a只是存储的是最终结果,

所以如果想重置a的索引,那么reset_index()中必须添加inplace=True.

a=df.pivot_table(values='orderamount',index='month',aggfunc=sum)
a.reset_index(inplace=True)
print(a)

b=df.pivot_table(values='orderamount',index='month',aggfunc=sum).reset_index()
print(b)

如果不想重置a的索引,但是想看索引重置后的格式,那么可以使用下面形式:

a=df.pivot_table(values='orderamount',index='month',aggfunc=sum)
d=a.reset_index()
print(a)
print("******")
print(d)

运行结果如下:

原文地址:https://www.cnblogs.com/bravesunforever/p/12129023.html