新浪博客

pandas reindex方法重排序索引和指定索引

2016-04-20 16:30阅读:
reindex方法重排序索引和指定索引,pandas调用reindex方法后净会根据新索引进行重排,并按指定的索引返回对应的内容
pandas对象的reindex方法,其作用是创建一个适应新索引的新对象,原对象不变
In [184]: df2.reindex([2,3,4,])
Out[184]:
zqmc zqdm
2 hsdz3 600573
3 hsdz4 600574
4 hsdz5 600575
[3 rows x 2 columns]
In [185]: df2
Out[185]:
zqmc zqdm
0 hddz1 600571
1 hsdz2 600572
2 hsdz3 600573
3 hsdz4 600574
4 hsdz5 600575
5 hsdz6 600576
6 hsdz7 600578
[7 rows x 2 col
umns]
pandas调用reindex方法后净会根据新索引进行重排,如果某个索引值当前不存在,就会引入
缺失值;可以通过fill_value参数填充默认值,也可以通过method参数设置填充方法;
In [186]: df2.reindex([8,5,3,4,],fill_value=0)
Out[186]:
zqmc zqdm
8 0 0
5 hsdz6 600576
3 hsdz4 600574
4 hsdz5 600575
[4 rows x 2 columns]
In [192]: df2.reindex(range(9),method='ffill')
Out[192]:
zqmc zqdm
0 hddz1 600571
1 hsdz2 600572
2 hsdz3 600573
3 hsdz4 600574
4 hsdz5 600575
5 hsdz6 600576
6 hsdz7 600578
7 hsdz7 600578
8 hsdz7 600578
[9 rows x 2 columns]
reindex方法的methon参数的选项:
ffill或pad 前向填充(或搬运)值
bfill或backfill 后向填充(或搬运)值
也可以通过columns参数对列进行重索引:
In [195]: df2.reindex(columns=['zqdm','zqmc','value'])
Out[195]:
zqdm zqmc value
0 600571 hddz1 NaN
1 600572 hsdz2 NaN
2 600573 hsdz3 NaN
3 600574 hsdz4 NaN
4 600575 hsdz5 NaN
5 600576 hsdz6 NaN
6 600578 hsdz7 NaN
[7 rows x 3 columns]

我的更多文章

下载客户端阅读体验更佳

APP专享