如何在Pandas数据框中重置索引?
在此程序中,我们将替换或换句话说,重置Pandas数据框中的默认索引。我们将首先创建一个数据框并查看默认索引,然后将该默认索引替换为我们的自定义索引。
算法
Step 1: Define your dataframe. Step 2: Define your own index. Step 3: Replace the default index with your index using the reset function in Pandas library.
范例程式码
import pandas as pd dataframe = {'Name':["Allen", "Jack", "Mark", "Vishal"],'Marks':[85,92,99,87]} df = pd.DataFrame(dataframe) print("Before using reset_index:\n", df) own_index = ['a', 'j', 'm', 'v'] df = pd.DataFrame(dataframe, own_index) df.reset_index(inplace = True) print("After using reset_index:\n", df)输出结果
Before using reset_index(): Name Marks 0 Allen 85 1 Jack 92 2 Mark 99 3 Vishal 87 After using reset_index(): index Name Marks 0 0 Allen 85 1 1 Jack 92 2 2 Mark 99 3 3 Vishal 87