官方參考鏈接:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html#pandas.DataFrame.set_index
Set the DataFrame index using existing columns.
Set the DataFrame index (row labels) using one or more existing columns or arrays (of the correct length). The index can replace the existing index or expand on it.
- Parameters
-
- keys label or array-like or list of labels/arrays
-
This parameter can be either a single column key, a single array of the same length as the calling DataFrame, or a list containing an arbitrary combination of column keys and arrays. Here, “array” encompasses
Series
,Index
,np.ndarray
, and instances ofIterator
. - drop bool, default True
-
Delete columns to be used as the new index.
- append bool, default False
-
Whether to append columns to existing index.
- inplace bool, default False
-
If True, modifies the DataFrame in place (do not create a new object).
- verify_integrity bool, default False
-
Check the new index for duplicates. Otherwise defer the check until necessary. Setting to False will improve the performance of this method.
- Returns
-
- DataFrame or None
-
Changed row labels or None if
inplace=True
.
個人理解:
這是一個設置index的命令,主要參數為keys. 這個參數可以式已經存在的df對象中的columns的名稱,也可以是一個單獨的數組對象,數組對象包含Series
, Index
, np.ndarray
, and instances of Iterator
.
drop :表示為是否丟棄設置為index的columns bool值,默認為true。
append: 是否為添加的索引,默認為flase,true會與源索引變成組合索引。
verify_integrity:檢查新索引是否有重復項,默認為false。
官方代碼實操學習
常規操作,設置一個列為index
In [32]: df = pd.DataFrame({'month': [1, 4, 7, 10], ...: 'year': [2012, 2014, 2013, 2014], ...: 'sale': [55, 40, 84, 31]}) In [33]: df Out[33]: month year sale 0 1 2012 55 1 4 2014 40 2 7 2013 84 3 10 2014 31 In [34]: df.set_index('month') Out[34]: year sale month 1 2012 55 4 2014 40 7 2013 84 10 2014 31
設置append為True,組合為聯合索引。
In [35]: df.set_index('year',append=True) Out[35]: month sale year 0 2012 1 55 1 2014 4 40 2 2013 7 84 3 2014 10 31
當然也可以通過設置多列,設置組合索引。
In [37]: df.set_index(['year','month']) Out[37]: sale year month 2012 1 55 2014 4 40 2013 7 84 2014 10 31 In [38]: In [38]: df.set_index([pd.Index([2,3,4,5]),'year']) Out[38]: month sale year 2 2012 1 55 3 2014 4 40 4 2013 7 84 5 2014 10 31
最后也可以設置外部傳入的可迭代對象為index
In [39]: new_index = list('abcd') In [40]: df.set_index([new_index]) Out[40]: month year sale a 1 2012 55 b 4 2014 40 c 7 2013 84 d 10 2014 31