Pandas警告:DeprecationWarning: .ix is deprecated.(ix、loc、iloc的区别)

ix和loc、iloc函数都是用来获取某一行或者某一列数据的。

请看如下案例:

import pandas as pd
data = [[1,2,3],[4,5,6],[7,8,9]]
rows = ['row1','row2','row3']#行标签
columns = ['col1','col2','col3']#列标签
df = pd.DataFrame(data, index=rows, columns=columns)
print df

运行结果:

 
 
      col1  col2  col3
row1     1     2     3
row2     4     5     6
row3     7     8     9

1.loc函数

官网解释

Purely label-location based indexer for selection by label.

.loc[] is primarily label based, but may also be used with a boolean array.

完全基于标签位置的索引器,所谓标签位置就是上面定义的'row1','row2'。

因此使用loc函数的时候,如果传入的不是标签而是下标将会导致如下错误:

扫描二维码关注公众号,回复: 1996565 查看本文章

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

使用方法(row1就是行标签)

print df.loc['row1']

运行结果:

col1    1
col2    2
col3    3
Name: row1, dtype: int64

2.iloc函数

官网解释

Purely integer-location based indexing for selection by position.

.iloc[] is primarily integer position based (from 0 to length-1 of the axis), but may also be used with a boolean array.

完全基于行号的索引器,所谓行号就是第0、1、2行。

因此使用iloc函数的时候,如果传入的不是行号而是标签将会导致如下错误:

TypeError: cannot do positional indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [row1] of <type 'str'>

使用方法(0就是行号)

print df.iloc[0]

运行结果:

col1    1
col2    2
col3    3
Name: row1, dtype: int64

3.ix函数

官网解释

A primarily label-location based indexer, with integer position fallback.

.ix[] supports mixed integer and label based access. It is primarily label based, but will fall back to integer positional access unless the corresponding axis is of integer type.

支持标签和行号混合的索引器,既可以通过标签也可以通过行号,还可以组合在一起(这个函数已经过期,建议使用上面两个函数替代

由于loc和iloc已经可以完成ix函数的工作,因此在后面ix函数有可能被移除,当前第一次运行ix函数的时候会有如下警告

 DeprecationWarning: 
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing

使用方法(loc和iloc的结合)

print df.ix[0]

print df.ix['row1']

print df.ix['row1',‘col1’]

print df.ix['row1',0]

运行结果:

col1    1
col2    2
col3    3
Name: row1, dtype: int64
col1    1
col2    2
col3    3
Name: row1, dtype: int64
1
1




猜你喜欢

转载自blog.csdn.net/u014525494/article/details/80156497
今日推荐