Pandas 重置索引未生效
Pandas reset index is not taking effect
我不确定我在哪里误入歧途,但我似乎无法重置数据帧上的索引。
当我 运行 test.head()
时,我得到以下输出:
如你所见,dataframe是一个slice,所以index是越界的。
我想做的是重置此数据框的索引。所以我运行test.reset_index(drop=True)
。这将输出以下内容:
这看起来像一个新索引,但它不是。 运行 test.head
再次,索引还是一样。尝试使用 lambda.apply
或 iterrows()
会导致数据帧出现问题。
我怎样才能真正重置索引?
reset_index
默认不修改DataFrame;它 returns 具有重置索引的 new DataFrame。如果要修改原来的,使用inplace
参数:df.reset_index(drop=True, inplace=True)
。或者,通过 df = df.reset_index(drop=True)
.
分配 reset_index
的结果
BrenBarn 的 作品。
以下内容也通过 this thread 起作用,这与其说是故障排除,不如说是对如何重置索引的阐述:
test = test.reset_index(drop=True)
我会在 code 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)
我不确定我在哪里误入歧途,但我似乎无法重置数据帧上的索引。
当我 运行 test.head()
时,我得到以下输出:
如你所见,dataframe是一个slice,所以index是越界的。
我想做的是重置此数据框的索引。所以我运行test.reset_index(drop=True)
。这将输出以下内容:
这看起来像一个新索引,但它不是。 运行 test.head
再次,索引还是一样。尝试使用 lambda.apply
或 iterrows()
会导致数据帧出现问题。
我怎样才能真正重置索引?
reset_index
默认不修改DataFrame;它 returns 具有重置索引的 new DataFrame。如果要修改原来的,使用inplace
参数:df.reset_index(drop=True, inplace=True)
。或者,通过 df = df.reset_index(drop=True)
.
reset_index
的结果
BrenBarn 的
以下内容也通过 this thread 起作用,这与其说是故障排除,不如说是对如何重置索引的阐述:
test = test.reset_index(drop=True)
我会在 code 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)