maxframe.dataframe.DataFrame.set_index#

DataFrame.set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False)#

使用现有列设置 DataFrame 索引。

使用一个或多个现有列设置 DataFrame 索引(行标签)。索引可以替换现有索引或对其进行扩展。

参数:
  • keys (label or array-like or list of labels) -- 此参数可以是单个列键,也可以是包含列键的列表。

  • drop (bool, default True) -- 删除要用作新索引的列。

  • append (bool, default False) -- 是否将列追加到现有索引。

  • inplace (bool, default False) -- 如果为 True,则就地修改 DataFrame(不创建新对象)。

  • verify_integrity (bool, default False) -- 检查新索引是否包含重复项。否则将推迟检查直到必要时。设置为 False 将提高此方法的性能。

返回:

更改后的行标签,如果 inplace=True 则为 None。

返回类型:

DataFrame or None

参见

DataFrame.reset_index

set_index 的反向操作。

DataFrame.reindex

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

DataFrame.reindex_like

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

示例

>>> import maxframe.dataframe as md
>>> df = md.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' 列创建 MultiIndex:

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