pandas学习之路

注意pandas 中的切片操作pd.loc[],pd.iloc[],pd.ix[]
在pandas中如果索引值不是字符型pd.loc[1:2]用数值进行切片就会报错,但是iloc[],pd.ix[],就不会报错,所以在切片的时候尽量还是不要用pd.loc[],避免不必要的麻烦。

data=pd.DataFrame(np.random.randn(5,4),columns=list('ABCD'),index=list('abcde'))
print(data)
data.loc[2:3]

结果报错:

TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [2] of <class 'int'>

但是用pd.iloc[],pd.ix[],就不会报错。
当索引值是数值型时。

data=pd.DataFrame(np.random.randn(5,4),columns=list('ABCD'),index=np.arange(5,dtype=float))
data.iloc[2:3]

结果:

	A	B	C	D
2.0	0.269179	-0.645991	0.240113	-0.427881

loc []标签索引
iloc[]值索引
ix[]二者的结合

猜你喜欢

转载自blog.csdn.net/weixin_43213268/article/details/89004324
今日推荐