pandas (loc、iloc、ix)的区别

loc:通过行标签索引数据

iloc:通过行号索引行数据

ix:通过行标签或行号索引数据(基于loc和iloc的混合)

代码:

import pandas as pd

data = [[1, 2, 3], [4, 5, 6]]
index = ['a', 'b']
column = ['left', 'center', 'right']

table = pd.DataFrame(data=data, index=index, columns=column)

print(table)

print("----------" + "loc()" + "------------")
print(table.loc['a'])                           # 获取行标签是"a"的一行数据

print("----------" + "iloc()" + "------------")
print(table.iloc[0])                          # 获取索引值为"0"的一行数据

print("----------" + "ix()" + "------------")
print(table.ix[0])                          # 无论输入的是"a"还是"0"都是获取第一行的数据

print("----------" + "ix()" + "------------")
print(table.ix['a'])

结果:

/usr/local/bin/python3.7 /Users/xiaolata/PycharmProjects/Qlearning/pand_test/panda02.py
   left  center  right
a     1       2      3
b     4       5      6
----------loc()------------
left      1
center    2
right     3
Name: a, dtype: int64
----------iloc()------------
left      1
center    2
right     3
Name: a, dtype: int64
----------ix()------------
left      1
center    2
right     3
Name: a, dtype: int64
----------ix()------------
left      1
center    2
right     3
Name: a, dtype: int64

分析:

loc()是根据table的行标签获取一行数据

iloc()是根据table的行索引获取一行数据

ix()是根据table的行标签或者行索引获取一行数据,使用该方法输入行标签或者行索引都是可以的。

posted @ 2019-07-09 22:52  马帅领  阅读(7289)  评论(0编辑  收藏  举报