Pandas索引操作

Pandas的索引操作

1、Series和DataFrame中的索引都是Index对象

import numpy as np
import pandas as pd

ps1 = pd.Series(range(5),index=['a','b','c','d','e'])
type(ps.index)
Out:pandas.core.indexes.base.Index

pd1 = pd.DataFrame(np.arange(9).reshape(3,3),index=['a','b','c'],columns=['A','B','C'])
type(pd1.index)
Out:pandas.core.indexes.base.Index

2、索引对象不可变,保证了数据的安全

ps.index[0]= 2
Out: # 索引不可变
TypeError                                 Traceback (most recent call last)
<ipython-input-7-da91721757ee> in <module>()
----> 1 ps.index[0]= 2

E:\Users\Administrator\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in __setitem__(self, key, value)
   2063 
   2064     def __setitem__(self, key, value):
-> 2065         raise TypeError("Index does not support mutable operations")
   2066 
   2067     def __getitem__(self, key):

TypeError: Index does not support mutable operations

常见的Index种类

  • Index,索引
  • Int64Index,整数索引
  • MultiIndex,层级索引
  • DatetimeIndex,时间戳类型

索引的一些基本操作

1、重新索引

# reindex 创建一个符合新索引的对象
ps2 = ps1.reindex(['a','b','c','d','e','f'])
ps2

# 导致都是空值的原因是:没有和ps1建立对应关系,所以再ps1中没有找到索引对应关系,就造成了空值
a   NaN
b   NaN
c   NaN
d   NaN
e   NaN
f   NaN
dtype: float64
    
# 重新定义ps1 的索引后,建立了对应关系:
Out:
a    0.0
b    1.0
c    2.0
d    3.0
e    4.0
f    NaN
dtype: float64
    
# 行索引重建
pd2 = pd1.reindex(['a','b','c','d'])
pd2
	A	B	C
a	0.0	1.0	2.0
b	3.0	4.0	5.0
c	6.0	7.0	8.0
d	NaN	NaN	NaN

# 列索引重建
pd3 = pd1.reindex(columns=['C','B','A'])
pd3
	C	B	A
a	2	1	0
b	5	4	3
c	8	7	6

2、增

#Series:
ps1
Out:
a    0
b    1
c    2
d    3
e    4
dtype: int64    
    
ps1['f']= 9   # 在原有的基础上增加数据
ps1
Out:
a    0
b    1
c    2
d    3
e    4
f    9
dtype: int64
    
s1 = pd.Series({'f':999})
ps3 = ps1.append(s1)
ps3
Out:
a      0
b      1
c      2
d      3
e      4
f      9
f    999
dtype: int64
    
#DataFrame 
pd1
Out:
	A	B	C
a	0	1	2
b	3	4	5
c	6	7	8

# 增加列  -- 在原有的基础上
pd1[4]=[10,11,12]  # 默认增加的是列
pd1
OUt:
	A	B	C	4
a	0	1	2	10
b	3	4	5	11
c	6	7	8	12

# 插入  -- 在原有的基础上
pd1.insert(0,'E',[9,99,999])  # 0 代表列的索引,'E'代表给这一列起的名字,[9,99,999] 给这一列赋值
pd1
Out:
	E	A	B	C	4
a	9	0	1	2	10
b	99	3	4	5	11
c	999	6	7	8	12

# 增加行
# 标签索引loc
pd1.loc['d'] = [1,2,2,3,4]
pd1
Out:
	E	A	B	C	4
a	9	0	1	2	10
b	99	3	4	5	11
c	999	6	7	8	12
d	1	2	2	3	4

row = {'E':6,'A':6,'B':6,'C':6,4:6} # 在原来的基础上,产生一个新的对象
pd5 = pd1.append(row,ignore_index=True) # 忽略原来的索引
pd5
Out:
	E	A	B	C	4
0	9	0	1	2	10
1	99	3	4	5	11
2	999	6	7	8	12
3	1	2	2	3	4
4	6	6	6	6	6

3、删

# del  : 都是在原有的基础上,会对元数据产生影响
ps1
Out:
a    0
b    1
c    2
d    3
e    4
f    9
dtype: int64
    
del ps1['b']
ps1
Out:
a    0
c    2
d    3
e    4
f    9
dtype: int64
    
pd1
Out:
	E	A	B	C	4
a	9	0	1	2	10
b	99	3	4	5	11
c	999	6	7	8	12
d	1	2	2	3	4

del pd1['E']
pd1
Out:
	A	B	C	4
a	0	1	2	10
b	3	4	5	11
c	6	7	8	12
d	2	2	3	4

del pd1['a']
pd1
Out:
# del  只能删除列
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'a'
# drop 删除轴上数据  不会对元数据产生影响,会生成新的数据
# 删除一条
# Series
ps6=ps1.drop('a')
ps6
Out:
c    2
d    3
e    4
f    9
dtype: int64

# 删除多条
ps1.drop(['a','c'])
Out:
d    3
e    4
f    9
dtype: int64

# dataframe
# 默认删除行
pd1.drop('a')
Out:
	A	B	C	4
b	3	4	5	11
c	6	7	8	12
d	2	2	3	4

pd1.drop(['a','b'])
Out:
	A	B	C	4
c	6	7	8	12
d	2	2	3	4

# 删除列
pd1.drop('A',axis=1) # 1 列   0 行
Out:
	B	C	4
a	1	2	10
b	4	5	11
c	7	8	12
d	2	3	4

pd1.drop('A',axis='columns')
Out:
	B	C	4
a	1	2	10
b	4	5	11
c	7	8	12
d	2	3	4

# inplace 属性 在原对象上删除,并不会返回新的对象
ps1
Out:
a    0
c    2
d    3
e    4
f    9
dtype: int64
    
ps1.drop('a',inplace=True)
ps1
Out:
c    2
d    3
e    4
f    9
dtype: int64

4、改

# 更新一下数据:
ps1 = pd.Series(range(5),index=['a','b','c','d','e'])
ps1
Out:
a    0
b    1
c    2
d    3
e    4
dtype: int64
    
pd1 = pd.DataFrame(np.arange(9).reshape(3,3),index=['a','b','c'],columns=['A','B','C'])
pd1
Out:
	A	B	C
a	0	1	2
b	3	4	5
c	6	7	8
# Series
ps1['a'] = 999  # 通过索引标签更改值
ps1
Out:
a    999
b      1
c      2
d      3
e      4
dtype: int64

ps1[0]= 888   # 通过行索引更改
ps1
Out:
a    888
b      1
c      2
d      3
e      4
dtype: int64
    
#DataFrame
# 直接使用索引
pd1['A'] = [6,6,6] # 通过列表修改 也可直接 = 9(则是一列数都等于9)
pd1
Out:
	A	B	C
a	6	1	2
b	6	4	5
c	6	7	8

# 对象.列
pd1.A = 6
pd1
Out:
	A	B	C
a	6	1	2
b	6	4	5
c	6	7	8

# 变成了增加列
pd1['a'] = 777 # 指定一个索引的话,优先是列,如果没有这一列,就会增加
pd1
Out:
A	B	C	a
a	6	1	2	777
b	6	4	5	777
c	6	7	8	777

# loc :标签索引
pd1.loc['a'] = 999
pd1
Out:
	A	B	C	a
a	999	999	999	999
b	6	4	5	777
c	6	7	8	777

pd1.loc['a','A'] = 1000  # 给具体位置赋值
pd1
Out:
	A	B	C	a
a	1000 999 999 999
b	6	4	5	777
c	6	7	8	777

5、查

# Series
# 1、行索引
ps1
Out:
a    888
b      1
c      2
d      3
e      4
dtype: int64
    
ps1['a']   # 标签索引
Out:
888
ps1[0]    # 位置索引
Out:
888    

#2、切片
# 位置切片索引
ps1[1:4]
Out:
b    1
c    2
d    3
dtype: int64
    
# 标签切片 按照索引名操作,是包含终止索引
ps1['b':'e']
Out:
b    1
c    2
d    3
e    4
dtype: int64
    
#3、不连续索引
ps1[['b','e']]  # 加两个中括号是代表不连续
Out:
b    1
e    4
dtype: int64

ps1[[0,2,3]]
Out:
a    888
c      2
d      3
dtype: int64

# 布尔索引
ps1[ps1>2]
Out:
a    888
d      3
e      4
dtype: int64
# dataframe
pd1
Out:
	A	B	C	a
a	1000 999 999 999
b	6	4	5	777
c	6	7	8	777

# 1、列索引
pd1['A']
Out:
a    1000
b       6
c       6
Name: A, dtype: int64

# 取多列
pd1[['A','C']]
Out:
	A	C
a	1000 999
b	6	5
c	6	8

# 2、切片
pd1[:2]
Out:
	A	B	C	a
a	1000 999 999 999
b	6	4	5	777
posted @   坤坤无敌  阅读(321)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
点击右上角即可分享
微信分享提示