pandas.DataFrame.set_index#

DataFrame.set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False)[源代码]#

使用现有列设置DataFrame索引。

使用一个或多个现有列或数组(具有正确长度)设置DataFrame索引(行标签)。该索引可以替换现有的索引或在其上进行扩展。

参数
keys标签或类似数组或标签/数组列表

此参数可以是单个列键、与调用DataFrame相同长度的单个数组,也可以是包含列键和数组的任意组合的列表。在这里,“数组”包含 SeriesIndexnp.ndarray ,和实例 Iterator

drop布尔值,默认为True

删除要用作新索引的列。

append布尔值,默认为False

是否将列追加到现有索引。

inplace布尔值,默认为False

如果为True,则就地修改DataFrame(不创建新对象)。

verify_integrity布尔值,默认为False

检查新索引中是否有重复项。否则,将支票推迟到必要时再开。设置为False将提高此方法的性能。

退货
DataFrame或无

如果行标签已更改,则为None inplace=True

参见

DataFrame.reset_index

与set_index相反。

DataFrame.reindex

更改为新索引或扩展索引。

DataFrame.reindex_like

更改为与其他DataFrame相同的索引。

示例

>>> df = pd.DataFrame({'month': [1, 4, 7, 10],
...                    'year': [2012, 2014, 2013, 2014],
...                    'sale': [55, 40, 84, 31]})
>>> df
   month  year  sale
0      1  2012    55
1      4  2014    40
2      7  2013    84
3     10  2014    31

将索引设置为‘Month’列:

>>> df.set_index('month')
       year  sale
month
1      2012    55
4      2014    40
7      2013    84
10     2014    31

使用列‘Year’和‘Month’创建多重索引:

>>> df.set_index(['year', 'month'])
            sale
year  month
2012  1     55
2014  4     40
2013  7     84
2014  10    31

使用索引和列创建多索引:

>>> df.set_index([pd.Index([1, 2, 3, 4]), 'year'])
         month  sale
   year
1  2012  1      55
2  2014  4      40
3  2013  7      84
4  2014  10     31

使用两个系列创建多索引:

>>> s = pd.Series([1, 2, 3, 4])
>>> df.set_index([s, s**2])
      month  year  sale
1 1       1  2012    55
2 4       4  2014    40
3 9       7  2013    84
4 16     10  2014    31