Pandas中loc,iloc,ix的区别
2017-12-26 20:53
781 查看
总结:
loc需要传入的是index的label。
iloc需要传入的是index的position(行号)
ix优先按label索引,如果找不到label,再按position索引。
例如:
比较下列三个的差异。
再比如:
s.loc[:6]找不到为6的label,所以发生了KeyError;因为索引号为整数类型,s.ix[:6]找不到label为6的,如果索引号为混合类型,则不会报错。
如:
对于DataFrame数据,如:
loc需要传入的是index的label。
iloc需要传入的是index的position(行号)
ix优先按label索引,如果找不到label,再按position索引。
例如:
>>> s = pd.Series(np.nan, index=[49,48,47,46,45, 1, 2, 3, 4, 5]) >>> s 49 NaN 48 NaN 47 NaN 46 NaN 45 NaN 1 NaN 2 NaN 3 NaN 4 NaN 5 NaN
比较下列三个的差异。
s.loc[:3] s.iloc[:3] s.ix[:3]
>>> s.loc[:3] 49 NaN 48 NaN 47 NaN 46 NaN 45 NaN 1 NaN 2 NaN 3 NaN # s.loc[:3] 返回的是直到索引label为3的所有行。
>>> s.iloc[:3] 49 NaN 48 NaN 47 NaN # s.iloc[:3]返回的是前三行。
>>> s.ix[:3] 49 NaN 48 NaN 47 NaN 46 NaN 45 NaN 1 NaN 2 NaN 3 NaN # s.ix[:3]先按label索引。
再比如:
>>> s.iloc[:6] 49 NaN 48 NaN 47 NaN 46 NaN 45 NaN 1 NaN >>> s.loc[:6] KeyError: 6 >>> s.ix[:6] KeyError: 6
s.loc[:6]找不到为6的label,所以发生了KeyError;因为索引号为整数类型,s.ix[:6]找不到label为6的,如果索引号为混合类型,则不会报错。
如:
>>> s2 = pd.Series(np.nan, index=['a','b','c','d','e', 1, 2, 3, 4, 5]) >>> s2.index.is_mixed() True >>> s2.ix[:6] a NaN b NaN c NaN d NaN e NaN 1 NaN >>> s2.ix[:'c'] a NaN b NaN c NaN
对于DataFrame数据,如:
>>> df = pd.DataFrame(np.nan, index=list('abcde'), columns=['x','y','z', 8, 9]) >>> df x y z 8 9 a NaN NaN NaN NaN NaN b NaN NaN NaN NaN NaN c NaN NaN NaN NaN NaN d NaN NaN NaN NaN NaN e NaN NaN NaN NaN NaN >>> df.ix[:'c', :4] x y z 8 a NaN NaN NaN NaN b NaN NaN NaN NaN c NaN NaN NaN NaN >>> df.iloc[:df.index.get_loc('c') + 1, :4] x y z 8 a NaN NaN NaN NaN b NaN NaN NaN NaN c NaN NaN NaN NaN
相关文章推荐
- Pandas中ix,loc,iloc有什么区别?
- python pandas (ix & iloc &loc) 的区别
- Pandas中ix,loc,iloc有什么区别?
- Pandas——ix vs loc vs iloc区别
- pandas中df.ix, df.loc, df.iloc 的使用场景以及区别
- python pandas (ix & iloc &loc) 的区别
- python pandas (ix & iloc &loc) 的区别
- python pandas (ix & iloc &loc) 的区别
- Pandas中ix,loc,iloc有什么区别?
- python pandas (ix & iloc &loc) 的区别
- python pandas中ix,iloc,loc的区别
- python pandas (ix & iloc &loc) 的区别
- python pandas.DataFrame选取、修改数据最好用.loc,.iloc,.ix
- pandas中loc、iloc、ix的区别
- 详谈Pandas中iloc和loc以及ix的区别
- pandas中Dataframe的查询方法([], loc, iloc, at, iat, ix)
- Pandas中iloc和loc以及ix的区别
- python pandas中的ix,loc和iloc
- 在pandas中, DataFrame的 ix(loc, iloc)属性的设置误区,以及reindex可以找到两个df不同之处
- Pandas的 loc iloc ix 区别