python中loc、iloc和ix函数区别和作用详解(附示例)

Pandas的基本数据结构是Series(数组)和DataFrame(类似二维数组),Pandas 提供了 Index 对象,每个 Series 都会带有一个对应的Index,用来标记不同的元素,Index 的内容不一定是数字,也可以是字母、中文等,它类似于SQL中的主键
当我们只想取数据中的各别行或列,可以用.loc .iloc .ix来实现:

1.loc意义:通过行标签索引行数据

loc[n]表示索引的是第n行(index是整数)
loc[‘n’]表示索引的是第‘n’行(index是字符)

2.iloc意义:通过行号获取行数据
3.ix:结合前两种的混合索引

三者区别

  1. ix / loc 可以通过行号和行标签进行索引,比如 df.loc[‘a’] , df.loc[1], df.ix[‘a’] , df.ix[1](这里的‘a’是行标签)
  2. iloc只能通过行号索引 , df.iloc[0] 是对的, 而df.iloc[‘a’] 是错误的
  3. .ix[0:n,列名]或.loc[0:n,列名]取数据时,是可以取到index=n这列的,因为此时0:n指的不是下标,而是index的名称。而iloc[0:n,列名]只能取到前n行,也就是index=n-1的行。

建议:当用行号索引的时候, 尽量用 iloc 来进行索引; 而用标签索引的时候用 loc , ix 尽量别用。

代码示例:

import pandas as pd
filename='ratings.csv'
data=pd.read_csv(filename,names=['user_id','movie_id','rating','time'], sep='::', engine='python')
 #数据集为movielens-1M中的ratings.csv数据
 
data_test1=data.iloc[:,:2]  #选取位置为[0,2)列的整列数据
data_test2=data.iloc[0:5,1]  #选取位置为1的列的[0,5)行的数据
 
data_test3=data.loc[0:2,'movie_id']  #选取列名为‘movie_id’的[0,2]行的数据
#loc[M:N,m:n]表示取M:N行的m到n-l列的数据

print('-------打印data_test1----------')
print(data_test1)
print('-------打印data_test2-------------------')
print(data_test2)
print('-------打印data_test3----------------------------')
print(data_test3)

输出结果:

-------打印data_test1----------
         user_id   movie_id
0               1      1193
1               1       661
2               1       914
3               1      3408
4               1      2355
...           ...       ...
1000204      6040      1091
1000205      6040      1094
1000206      6040       562
1000207      6040      1096
1000208      6040      1097

[1000209 rows x 2 columns]

-------打印data_test2-------------------
0    1193
1     661
2     914
3    3408
4    2355
Name: movie_id, dtype: int64
-------打印data_test3----------------------------
0    1193
1     661
2     914
Name: movie_id, dtype: int64
发布了13 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43631296/article/details/105237694
今日推荐