如何重置 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

更新日期:2021 年 3 月 16 日

332 次瀏覽

開啟你的 職業

完成課程即可獲得認證

開始學習
廣告