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

相关推荐