pandas Series 的索引对象(一)

建一个Series

from pandas import Series,DataFrame

obj=Series(range(3),index=['a','b','c'])

obj
Out[8]: 
a    0
b    1
c    2
dtype: int32
index=obj.index

index
Out[10]: Index(['a', 'b', 'c'], dtype='object')
index[1:]
Out[11]: Index(['b', 'c'], dtype='object')

按照index 重新排序

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

obj
Out[25]: 
d    4.5
b    7.2
a   -5.3
c    3.6
dtype: float64

obj2=obj.reindex(['a','b','c','d','e'])

obj2
Out[27]: 
a   -5.3
b    7.2
c    3.6
d    4.5
e    NaN
dtype: float64

ffill 前向排列

obj3=Series(['blue','purple','yellow'],index=[0,2,4])

obj3
Out[29]: 
0      blue
2    purple
4    yellow
dtype: object

obj3.reindex(range(6),method='ffill')
Out[30]: 
0      blue
1      blue
2    purple
3    purple
4    yellow
5    yellow
dtype: object

pad=ffill也是前向排列

obj3.reindex(range(6),method='pad')
Out[31]: 
0      blue
1      blue
2    purple
3    purple
4    yellow
5    yellow
dtype: object

bfill后向排列 =backfill

obj3.reindex(range(6),method='bfill')
Out[32]: 
0      blue
1    purple
2    purple
3    yellow
4    yellow
5       NaN
dtype: object
posted @ 2022-08-19 23:00  luoganttcc  阅读(22)  评论(0编辑  收藏  举报