我不确定我在哪里误入歧途,但我似乎无法重置数据帧上的索引。
当我运行test.head()
时,我得到以下输出:
如您所见,数据帧是一个切片,因此索引超出范围。我想要做的是重置此数据帧的索引。所以我运行test.reset_index(drop=True)
。这输出如下:
这看起来像一个新的索引,但事实并非如此。再次运行test.head
,指数仍然相同。尝试使用lambda.apply
或iterrows()
会导致数据帧出现问题。
我怎样才能真正重置索引?
reset_index
默认不修改DataFrame;它返回一个带有重置索引的新DataFrame。如果要修改原始文件,请使用inplace
参数:df.reset_index(drop=True, inplace=True)
。或者,通过执行reset_index
分配df = df.reset_index(drop=True)
的结果。
我会在代码veritas的答案中添加:
如果您已经指定了索引列,那么您当然可以保存del。在我的假设例子中:
df_total_sales_customers = pd.DataFrame({'Sales': total_sales_customers['Sales'],
'Customers': total_sales_customers['Customers']}, index = total_sales_customers.index)
df_total_sales_customers = df_total_sales_customers.reset_index()
作为in code veritas答案的延伸......而不是在最后做del
:
test = test.reset_index()
del test['index']
你可以设置下降到True
。
test = test.reset_index(drop=True)