本篇内容主要讲解“Pandas中DataFrame的重新索引实例分析”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Pandas中DataFrame的重新索引实例分析”吧!
默认对行索引,加上关键字columns对列索引。
import pandas as pd
data=[[1,1,1,1],[2,2,2,2],[3,3,3,3],[4,4,4,4]]
df = pd.DataFrame(data,index=['d','b','c','a'])
print(df)
默认对列索引:如果是新的索引名将会用NaN
df=df.reindex(['a','b','c','d','e'])
print(df)
加上关键字columns对列重新索引:
df=df.reindex(columns=[2,1,3,4,0])
print(df)
对于index为有序的数据,我们有时候可能会进行一些插值处理,只需要在reindex加上method参数即可,参数如下表
(图片来源:截图于 利用python进行数据分析 Wes McKinney 著)
例子:
import pandas as pd
data=[[1,1,1,1],[2,2,2,2],[3,3,3,3]]
df = pd.DataFrame(data,index=range(3))
print(df)
df=df.reindex([0,1,2,3,4,5],method='ffill')
print('--------------')
print(df)
reindex函数的相关参数:
import pandas as pd
import numpy as np
a=pd.DataFrame(np.random.randint(1,10,20).reshape(4,5))
print(a)
0 1 2 3 4
0 1 3 2 7 6
1 8 2 2 7 2
2 2 6 6 2 5
3 4 1 6 8 9
b=a.sort_values(by=4)
print(b)
0 1 2 3 4
1 8 2 2 7 2
2 2 6 6 2 5
0 1 3 2 7 6
3 4 1 6 8 9
### 重置索引:方法1
c=a.sort_values(by=4,ignore_index=True)
print(c)
0 1 2 3 4
0 8 2 2 7 2
1 2 6 6 2 5
2 1 3 2 7 6
3 4 1 6 8 9
### 重置索引:方法2
d=b.reset_index(drop=True)
print(d)
0 1 2 3 4
0 8 2 2 7 2
1 2 6 6 2 5
2 1 3 2 7 6
3 4 1 6 8 9
到此,相信大家对“Pandas中DataFrame的重新索引实例分析”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。