大数据知识体系
首页
数据结构与算法
  • JVM
  • Java
  • Scala
  • Python
设计模式
  • MySQL
  • Redis
  • HDFS
  • HBase
  • ClickHouse
  • ElasticSearch
  • Iceberg
  • Hudi
  • Spark
  • Flink
  • Hive
  • Yarn
  • Zookeeper
  • Maven
  • Git
  • 数据仓库
  • 用户画像
  • 指标体系
数据治理
关于
首页
数据结构与算法
  • JVM
  • Java
  • Scala
  • Python
设计模式
  • MySQL
  • Redis
  • HDFS
  • HBase
  • ClickHouse
  • ElasticSearch
  • Iceberg
  • Hudi
  • Spark
  • Flink
  • Hive
  • Yarn
  • Zookeeper
  • Maven
  • Git
  • 数据仓库
  • 用户画像
  • 指标体系
数据治理
关于
  • JVM

    • JVM 架构
    • JVM 类加载机制
    • JVM 运行时数据区
    • JVM 垃圾回收机制
    • JVM 性能监控与调优
    • JVM 常见错误
  • Java

    • Java基础

      • Java 基础知识
      • Java 基础 - 枚举类
      • Java 基础 - 异常处理
      • Java 基础 - 泛型
      • Java 基础 - 反射
      • Java 基础 - 代理模式
      • Java 基础 - 注解
    • Java集合

    • Java并发编程

    • Java 开发规范
  • Scala

    • Scala 概述
  • Python

    • Numpy

      • 初识 Numpy
      • ndarray 的创建方式
      • NumPy 的数据类型
      • NumPy 数组计算
      • 拷贝
      • 索引和切片
      • 数学和统计方法
      • 数组形状变换
      • 通用函数
      • 排序
      • 搜索和计数
      • 线性代数
      • 伪随机数生成
      • 广播
      • 文件输入和输出
    • Pandas

      • 初识 Pandas
      • 认识 Series 和 DataFrame
      • Series 和 DataFrame 增删改查
      • Index对象增删改查
        • 单层索引
          • 创建
          • 查
          • 改索引名
          • 直接改
          • 函数改
          • 增
          • 按位置添加一行
          • 尾部添加多行
          • 并
          • 删
          • 按位置删除一行
          • 按索引删除多行
          • 交
        • 多层索引
          • 创建
          • 从数组或者列表(元组)创建
          • 从多个可迭代对象的笛卡尔积创建
          • 从 DataFrame 创建
          • 查
          • 改
          • 改索引名(函数改)
          • 改索引层次顺序
      • 普通列和行Index相互转化
      • 快速查看整体信息
      • 数值运算
      • 合并数据集
      • 数值统计与聚合
      • 分组聚合
      • 分类类型
      • 排序和排名
      • 时间序列
      • 文件输入与输出
      • 缺失值处理
      • 字符串处理
      • pandas sql
      • 其它
  • 语言基础
  • Python
  • Pandas
Will
2022-08-04
目录

Index对象增删改查

import numpy as np
import pandas as pd
1
2

# 单层索引

# 创建

pd.Index(data=None, dtype=None, copy=False, name=None, fastpath=None, tupleize_cols=True, **kwargs)

  • name:一维列表
  • dtype:索引元素的类型,默认为 object 型
  • name:索引的名字,类似于列的名字
data = ['a', 'b', 'c', 'd']
index = pd.Index(data, name='first_index')
index
1
2
3
Index(['a', 'b', 'c', 'd'], dtype='object', name='first_index')

从返回值可以看到,index 由三部分组成,可以分别查看。

index.values
1
array(['a', 'b', 'c', 'd'], dtype=object)
index.name
1
'first_index'
index.dtype
1
dtype('O')

# 查

  • 查询方式和一维 ndarray 或 Series 的.iloc[]完全一样。
index[0] # scalar,返回值
1
'a'
index[0:2] # 范围,返回index
1
Index(['a', 'b'], dtype='object', name='first_index')
index[[0, 2]] # 列表,返回index
1
Index(['a', 'c'], dtype='object', name='first_index')
mask = [True, False, True, False]  # mask,返回index
index[mask]
1
2
Index(['a', 'c'], dtype='object', name='first_index')

# 改索引名

虽然索引的值是不能修改的,但是名字确是可以修改的。

# 直接改

index.name = 'second_name'
index
1
2
Index(['a', 'b', 'c', 'd'], dtype='object', name='second_name')

# 函数改

index.set_names(names, level=None, inplace=False)

  • names:要设置的名字,可以为名字的列表
  • level:索引级别
  • inplace:是否原地修改
index.set_names('third_name')
1
Index(['a', 'b', 'c', 'd'], dtype='object', name='third_name')

# 增

# 按位置添加一行

Index.insert(loc, value)

  • loc:位置编号
  • value:值
index
1
Index(['a', 'b', 'c', 'd'], dtype='object', name='second_name')
index.insert(1, 'f') # 未修改原对象
index
1
2
Index(['a', 'f', 'b', 'c', 'd'], dtype='object', name='second_name')

Index(['a', 'b', 'c', 'd'], dtype='object', name='second_name')

# 尾部添加多行

Index.append(other)

  • other:其他索引对象
index1 = index.copy()
index1
1
2
Index(['a', 'b', 'c', 'd'], dtype='object', name='second_name')
index1.append(index)
1
Index(['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'], dtype='object', name='second_name')

# 并

Index.union(other)

index2 = pd.Index(['b','c','d'])
index2
1
2
Index(['b', 'c', 'd'], dtype='object')
index1.union(index2)
1
Index(['a', 'b', 'c', 'd'], dtype='object')

# 删

# 按位置删除一行

Index.delete(loc)

  • loc:位置编号
index1.delete(1)
1
Index(['a', 'c', 'd'], dtype='object', name='second_name')

# 按索引删除多行

Index.drop(labels)

  • labels:索引列表
index1.drop(['a','b'])
1
Index(['c', 'd'], dtype='object', name='second_name')

# 交

Index.intersection(other)

index1.intersection(index2)
1
Index(['b', 'c', 'd'], dtype='object')

# 多层索引

# 创建

# 从数组或者列表(元组)创建

pd.MultiIndex.from_arrays(arrays, sortorder=None, names=None)

pd.MultiIndex.from_tuples(tuples, sortorder=None, names=None)

  • arrays / tuples:数组、元组或列表
  • sortorder:排序等级
  • names:索引中级别的名称
data = [['a','one'],['a','two'],['b','one']]
# data = [('a','one'),('a','two'),('b','one')]
index1 = pd.MultiIndex.from_tuples(data, names=['name1', 'name2'])
index1
1
2
3
4
MultiIndex([('a', 'one'),
            ('a', 'two'),
            ('b', 'one')],
           names=['name1', 'name2'])
s1 = pd.Series([1,2,3], index=index1)
s1
1
2
name1  name2
a      one      1
       two      2
b      one      3
dtype: int64

# 从多个可迭代对象的笛卡尔积创建

pd.MultiIndex.from_product(iterables, sortorder=None, names=None)

  • iterables: 列表或者可迭代序列
  • sortorder:排序等级
  • names: 索引中级别的名称
iterables = [['bar', 'baz', 'foo', 'qux'], ['one', 'two']]
index2 = pd.MultiIndex.from_product(iterables, names=['first', 'second'])
index2
1
2
3
MultiIndex([('bar', 'one'),
            ('bar', 'two'),
            ('baz', 'one'),
            ('baz', 'two'),
            ('foo', 'one'),
            ('foo', 'two'),
            ('qux', 'one'),
            ('qux', 'two')],
           names=['first', 'second'])
s2 = pd.Series([1, 2, 3, 4, 5, 6, 7, 8], index=index2)
s2
1
2
first  second
bar    one       1
       two       2
baz    one       3
       two       4
foo    one       5
       two       6
qux    one       7
       two       8
dtype: int64

# 从 DataFrame 创建

0.24.0 版本新增

pd.MultiIndex.from_frame(df, sortorder=None, names=None)

  • df: DataFrame 对象
  • sortorder:排序等级
  • names: 索引中级别的名称
df = pd.DataFrame([['bar', 'one'], ['bar', 'two'], ['foo', 'one'], ['foo', 'two']], columns=['first', 'second'])
df
1
2
first second
0 bar one
1 bar two
2 foo one
3 foo two
index3 = pd.MultiIndex.from_frame(df)
index3
1
2
MultiIndex([('bar', 'one'),
            ('bar', 'two'),
            ('foo', 'one'),
            ('foo', 'two')],
           names=['first', 'second'])
s3 = pd.Series([1, 2, 3, 4], index=index3)
s3
1
2
first  second
bar    one       1
       two       2
foo    one       3
       two       4
dtype: int64

以上部分是显式地创建一个 MultiIndex 对象,但是在我们可以将数组或者列表直接传递到 Series/DataFrame 中,让其自动构造一个 MultiIndex。

index = [['one', 'one', 'two', 'two'], ['A', 'B', 'A', 'B']]
s4 = pd.Series([1, 2, 3, 4], index=index)
s4
1
2
3
one  A    1
     B    2
two  A    3
     B    4
dtype: int64
index4 = s4.index
index4
1
2
MultiIndex([('one', 'A'),
            ('one', 'B'),
            ('two', 'A'),
            ('two', 'B')],
           )

# 查

  • 查询方法和单层索引完全一致。
index4[0]  # scalar,返回值
1
('one', 'A')
index4[0:2]  # 范围,返回MultiIndex
1
MultiIndex([('one', 'A'),
            ('one', 'B')],
           )
index4[[0, 2]] # 列表,返回MultiIndex
1
MultiIndex([('one', 'A'),
            ('two', 'A')],
           )
mask = [True, False, True, False] # mask,返回MultiIndex
index4[mask]
1
2
MultiIndex([('one', 'A'),
            ('two', 'A')],
           )

获取某一层索引:MultiIndex.get_level_values(level)

  • level:int,选中的那一层
index4.get_level_values(0)
1
Index(['one', 'one', 'two', 'two'], dtype='object')
index4.get_level_values(1)
1
Index(['A', 'B', 'A', 'B'], dtype='object')

# 改

# 改索引名(函数改)

MultiIndex.set_names(names, level=None, inplace=False)

  • names:要设置的名字,可以为名字的列表;
  • level:多层索引需要设置修改的索引层次,可以为列表,要与 names 匹配;
  • inplace:是否原地修改。
index4.set_names('new_name_1', level=0)
1
MultiIndex([('one', 'A'),
            ('one', 'B'),
            ('two', 'A'),
            ('two', 'B')],
           names=['new_name_1', None])
index4.set_names(['new_name_2', 'new_name_3']) # 传入列表
1
MultiIndex([('one', 'A'),
            ('one', 'B'),
            ('two', 'A'),
            ('two', 'B')],
           names=['new_name_2', 'new_name_3'])

# 改索引层次顺序

MultiIndex.swaplevel(i=-2, j=-1)

  • 改变 level i 和 level j 的次序
index4.swaplevel()
1
MultiIndex([('A', 'one'),
            ('B', 'one'),
            ('A', 'two'),
            ('B', 'two')],
           )

Series.swaplevel(i=-2, j=-1)

DataFrame.swaplevel(i=-2, j=-1, axis = 1)

  • axis:0-行索引,1-列索引。 这两个函数更实用一些。
s4
1
one  A    1
     B    2
two  A    3
     B    4
dtype: int64
s4.swaplevel()
1
A  one    1
B  one    2
A  two    3
B  two    4
dtype: int64
columns = index4.copy()
columns.set_names(names=['name3','name4'], level=[0,1], inplace=True) #列索引取和行索引相同,只是改了名字
df = pd.DataFrame([[1, 2, 3, 4],[4, 5, 6, 7],[7, 8, 9, 10], [10, 11, 12, 13]], index=index4, columns=columns)
df
1
2
3
4
name3 one two
name4 A B A B
one A 1 2 3 4
B 4 5 6 7
two A 7 8 9 10
B 10 11 12 13
df.swaplevel(axis =1)  # 交换列索引顺序
1
name4 A B A B
name3 one one two two
one A 1 2 3 4
B 4 5 6 7
two A 7 8 9 10
B 10 11 12 13
上次更新: 2023/11/01, 03:11:44

← Series 和 DataFrame 增删改查 普通列和行Index相互转化→

Theme by Vdoing | Copyright © 2022-2023 Will 蜀ICP备2022002285号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式