如何在 Pandas 中重置分層索引?
要重置 Pandas 中的分層索引,我們可以使用 reset_index() 方法。
步驟
建立一個二維、大小可變的、潛在異構的表格資料 df。
列印輸入 DataFrame。
使用 groupby 獲取分層索引的不同級別並對其進行計數。
列印多層次索引 DataFrame。
使用 df.reset_index() 重置多層次索引 DataFrame。
列印新的更新後的 DataFrame。
示例
import pandas as pd df = pd.DataFrame({"x": [5, 2, 1, 9], "y": [4, 1, 5, 10]}) print "Input DataFrame is:
", df df1 = df.groupby(["x", "y"]).count() print "Hierarchical Index of input DataFrame is:
", df1 df2 = df1.reset_index() print "After resetting:
", df2
輸出
Input DataFrame is: x y 0 5 4 1 2 1 2 1 5 3 9 10 Hierarchical Index of input DataFrame is: Empty DataFrame Columns: [] Index: [(1, 5), (2, 1), (5, 4), (9, 10)] After resetting: x y 0 1 5 1 2 1 2 5 4 3 9 10
廣告