pandas.DataFrame.set_index#
- DataFrame.set_index(keys, *, drop=True, append=False, inplace=False, verify_integrity=False)[源代码]#
使用现有列设置 DataFrame 索引。
使用一个或多个现有列或数组(长度正确)设置 DataFrame 索引(行标签)。索引可以替换现有索引或扩展现有索引。
- Parameters:
- keys标签或类列表或标签/数组列表
此参数可以是单个列键、与调用 DataFrame 相同长度的单个数组,或包含列键和数组任意组合的列表。此处,“数组”包括
Series、Index、np.ndarray和Iterator的实例。- dropbool, default True
删除将用作新索引的列。
- appendbool,默认 False
是否将列追加到现有索引。
- inplacebool,默认 False
是修改 DataFrame 还是创建新的 DataFrame。
- verify_integritybool,默认 False
检查新索引是否存在重复项。否则,将检查推迟到必要时进行。设置为 False 将提高此方法的性能。
- Returns:
- DataFrame 或 None
已更改的行标签,如果
inplace=True则为 None。
参见
DataFrame.reset_indexset_index 的反操作。
DataFrame.reindex更改为新索引或扩展索引。
DataFrame.reindex_like将此对象更改为与另一个 DataFrame 具有相同的索引。
Examples
>>> 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’ 列创建 MultiIndex:
>>> df.set_index(['year', 'month']) sale year month 2012 1 55 2014 4 40 2013 7 84 2014 10 31
使用 Index 和列创建 MultiIndex:
>>> 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
使用两个 Series 创建 MultiIndex:
>>> 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