Pandas set_index 用法

set_index 仅适用于 DataFrame, 作用是重新设置 DataFrame 的行索引

创建示例数据, 行索引默认使用整数索引

In [1]: import pandas as pd

In [2]:
   ...: df = pd.DataFrame({"month": [2, 6, 12, 10], "year": [2008, 2012, 2012, 2019], "day": [29, 30, 31, 31]})

In [3]: df
Out[3]:
   month  year  day
0      2  2008   29
1      6  2012   30
2     12  2012   31
3     10  2019   31

可以使用已有的列替换默认的整数行索引

In [4]: df.set_index("year")
Out[4]:
      month  day
year
2008      2   29
2012      6   30
2012     12   31
2019     10   31

替换行索引后该列默认被删除, 可以设置 drop=False 保留该列

In [5]: df.set_index("year", drop=False)
Out[5]:
      month  year  day
year
2008      2  2008   29
2012      6  2012   30
2012     12  2012   31
2019     10  2019   31

可以使用多个列去替换行索引, 这样将形成层级索引

In [6]: df.set_index(["year", "month"])
Out[6]:
            day
year month
2008 2       29
2012 6       30
     12      31
2019 10      31

注意第3行的年份是空白, 表示与上一行相同

除了使用已有的列, 还可以使用自定义数据

In [8]: df.set_index([pd.Index([3, 3, 9, 11], name="other"), "year"])
Out[8]:
            month  day
other year
3     2008      2   29
      2012      6   30
9     2012     12   31
11    2019     10   31

在 Pandas 中, 使用 pd.Index 对象表示索引, 该对象是不可变对象

设置 append=True 可以将已有列附加到行索引, 这样就不是替换效果了

In [9]: df.set_index("year", append=True)
Out[9]:
        month  day
  year
0 2008      2   29
1 2012      6   30
2 2012     12   31
3 2019     10   31

对于 df 对象, 原有的索引是整数索引, 现在加入年份列, 变成层级索引, 第一层是整数索引, 第二层是年份

最后还有一个参数 inplace=True 表示直接修改 df, 而不是返回新对象

Original: https://blog.csdn.net/jiang_huixin/article/details/113042431
Author: jiang_huixin
Title: Pandas set_index 用法

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/676087/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球