pandas入门:索引对象,重建索引,轴向上删除条目,索引,选择与过滤

索引对象

pandas中的索引对象是用来存储轴标签和其他元数据的(例如轴名称或标签)。在构造series 或 dataframe 时,你所使用的任意数字或标签序列都可以在内部转换为索引对象。

obj = pd.Series(range(3),index=['a','b','c'])
index=obj.index
index[1:]
Index(['b', 'c'], dtype='object')

index[1]='d'  # TypeError   索引对象不可改变,用户时无法修改的。


labels=pd.Index(np.arange(3))
labels
Int64Index([0, 1, 2], dtype='int64')
obj2=pd.Series([1.5,-2.5,0],index=labels)     # 索引对象的不变性,可以在多种数据结构中分享索引。
obj2
0    1.5
1   -2.5
2    0.0
dtype: float64
obj2.index is labels
True

与python集合不同,pandas索引对象可以包含重复标签,根据重复标签进行筛选,会选出所有重复标签对应的数据。
在这里插入图片描述

重建索引

reindex 时pandas 对象重要的方法。该方法用于创建一个符合新索引的新对象。

obj=pd.Series([4.5,7.3,-5.3,3.6],index=['d','b','a','c'])

# series 调用 reindex 方法时,会将数据按照新的索引排序,不存在的就引入缺失值
obj2=obj.reindex(['a','b','c','d','e'])
obj2
a   -5.3
b    7.3
c    3.6
d    4.5
e    NaN
dtype: float64

对于顺序数据,比如时间序列,在重建索引时可能会需要进行插值或填值。 method 可选参数允许我们使用诸如 ffill 等方法在重建索引时插值,ffill 方法会将值前向填充。bfill 向后填充。

obj3=pd.Series(np.arange(3),index=[0,2,4])
obj3.reindex(range(6),method='ffill')
0    0
1    0
2    1
3    1
4    2
5    2
dtype: int32

在 dataframe 中, reindex 可以改变行索引,列索引,也可以同时改变二者。当仅传入一个序列时,结果的行会重建索引。

frame = pd.DataFrame(np.arange(9).reshape((3,3)),index=['a','b','c'],
                     columns=['ohio','texas','california'])
frame
	ohio	texas	california
a	0	1	2
b	3	4	5
c	6	7	8

frame.reindex(['d','c','b','b'])
	ohio	texas	california
d	NaN	NaN	NaN
c	6.0	7.0	8.0
b	3.0	4.0	5.0
b	3.0	4.0	5.0

frame.reindex(columns=['texas','utah','california'])      # 列可以使用columns 关键字重建索引。
	texas	utah	california
a	1	NaN	2
b	4	NaN	5
c	7	NaN	8

frame.loc[['d','c','b','b'],['texas','utah','california'])   # 使用loc 可以更加简洁。。。
reindex 方法的参数 描述
index 新建作为索引的序列,可以是索引是或任意其他序列型python 数据结构,索引使用时无需复制(?)
method 插值方式,ffill 为向前填充,bfill 向后填充
fill_value 通过重新索引引入缺失数据时使用的替代值
limit 当向前或向后填充时,所需填充的最大尺寸间隙(以元素为单位)
tolerance 当向前或向后填充时,所需填充的不精确匹配下的最大尺寸间隙(以绝对数字距离)
level 匹配 MultiIndex 级别的简单索引,否则选择子集/???
copy 默认时True ,即使新索引等于旧索引,也总是复制底层数据;如果时False,则在索引相同时不要复制数据。

轴向上删除条目

如果你已经拥有索引数组或不含条目的列表,在轴向上删除一个或更多的条目就很简单,但是需要一些数据操作和集合逻辑,drop 方法返回一个含有指示值或轴向上删除值的新对象。

obj = pd.Series(np.arange(5),index=['a','b','c','d','e'])
new_obj=obj.drop(['c','d'])
new_obj
a    0
b    1
e    4
dtype: int32

frame = pd.DataFrame(np.arange(9).reshape((3,3)),index=['a','b','c'],
                     columns=['ohio','texas','california'])
frame.drop(['a','c'])      # 删除轴 0 的元素
  ohio	texas	california
b	3	4	5

data.drop('ohio',anis=1)    # 可以传递anis=1 或 axis='columns' 来从列中删除

# 很多函数时,例如drop 会修改 series dataframe 的尺寸或形状,但是不会改变原对象
obj.drop('c',inplace=True)   # 这个参数清除被删除的数据,会作用到原来的对象。

索引,选择与过滤

series 的索引与 numpy 数组索引类似,但 series 的索引值可以不仅仅是整数。

obj = pd.Series(np.arange(5),index=['a','b','c','d','e'])
obj
a    0
b    1
c    2
d    3
e    4
dtype: int32
print(obj['b'],obj[1])
1	1

obj[2:4]
c    2
d    3
dtype: int32

obj[['b','a','d']]
b    1
a    0
d    3
dtype: int32

obj[[1,3]]
b    1
d    3
dtype: int32

obj[obj<2]
a    0
b    1	
dtype: int32


obj['b':'d']            # 普通的python切片中是不包含尾部的,series 的切片就不同了
b    1
c    2                 # 另外 obj['b':'d'] = 5  这样会修改原来的 series
d    3
dtype: int32

--------------------------我是分割线-----------------------------------------

frame = pd.DataFrame(np.arange(9).reshape((3,3)),index=['a','b','c'],
                     columns=['ohio','texas','california'])

  ohio	texas california
a	0	1	2
b	3	4	5
c	6	7	8

frame[['ohio','california']]
 ohio	california
a	0	2
b	3	5
c	6	8

frame[:2]
  ohio	texas	california
a	0	1	2
b	3	4	5

frame[frame['california']>5]
	ohio	texas	california
c	6	7	8

frame <5
	ohio	texas	california
a	True	True	True
b	True	True	False
c	False	False	False
frame[frame <5]=0
frame
	ohio	texas	california
a	0	0	0
b	0	0	5
c	6	7	8

猜你喜欢

转载自blog.csdn.net/weixin_46192930/article/details/106438727