如何重置 Pandas 数据帧中的 index?
在本教程中,我们将在 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
广告