Python学习(十三)——pandas函数库2

来源:互联网 发布:xshell连接linux 编辑:程序博客网 时间:2024/06/05 05:04

重新索引

创建一个适应新索引的新对象,该Series的reindex将会根据新索引进行重新排列。如果某个索引值不存在,就引入缺失值。
对于时间序列这样的有序数据,重新索引时可能需要做一些插值处理。method选项即可达到此目的。
1、重新索引
如,构造一个Series:

ser0=Series([101,202,303,404],index=['one','two','three','four'])print ser0

输出:

one      101two      202three    303four     404dtype: int64

进行重新索引:

ser1=ser0.reindex(['three','two','four','one'])print ser1

输出:

three    303two      202four     404one      101dtype: int64

2、对于新出现的索引,则引入缺失值:

ser1=ser0.reindex(['three','two','four','one','ten'])print ser1

输出:

three    303.0two      202.0four     404.0one      101.0ten        NaNdtype: float64

3、未指定缺失值时默认填充为NaN,也可以通过fill_value指定填充值:

ser1=ser0.reindex(['three','two','four','one','ten'],fill_value=10)print ser1

输出:

three    303two      202four     404one      101ten       10dtype: int64

4、重新索引并通过method指定填充元素的方法

ser0=Series([101,202,303],index=[0,3,6])ser1=ser0.reindex(range(9),method='ffill')print ser1

输出:

0    1011    1012    1013    2024    2025    2026    3037    3038    303dtype: int64

‘ffill’代表如果该行的值为空,则用前一行

原创粉丝点击