iloc、loc、ix总结

本文详细解析了Pandas中loc、iloc和ix三种索引方式的使用方法,包括单行、单列、多行和多列数据的索引操作,以及它们在行标签和行号上的应用区别。

中山大学菜鸡又来总结了。大佬言,你尽管总结,有人看算我输。
哦嚯嚯嚯嚯嚯嚯:)

import pandas as pd

data=[[1,2,3],[4,5,6]]
index=['a','b']#行号
columns=['c','d','e']#列号
df=pd.DataFrame(data,index=index,columns=columns)#生成一个数据框

index1=[0,'1']
columns1=[2,3,4]
df1=pd.DataFrame(data,index=index1,columns=columns1)

一、分别使用loc、iloc、ix 索引第一/n行的数据:

#1、直接[]
print(df[1:2])#数字表示行数
#    c  d  e
# b  4  5  6


#2、loc的单[]。只能用索引标签,不能用行数。
print(df.loc['a'])
# c    1
# d    2
# e    3
# Name: a, dtype: int64
print(df.loc[0])#报错


#3、loc的双[[]]。可以用索引标签,可以用行数,表现形式与loc的单[]不同。
print(df.loc[['a']])
#    c  d  e
# a  1  2  3
print(df1.loc[[0]])#数字代表索引名称。0表示index的名字,index名字里的0是个int
#    c  d  e
# a  1  2  3
print(df1.loc[['1']])#数字代表索引名称。1表示index的名字,index名字里的1是个str
#    2  3  4
# 1  4  5  6


#4、iloc的单[]。只能用行数,不能用索引标签。
print(df.iloc[0])#数字代表行数
# c    1
# d    2
# e    3
# Name: a, dtype: int64
print(df.iloc['a'])#报错


#5、iloc的双[]。只能用行数,不能用索引标签。
print(df.iloc[[0]])#数字代表行数
#    c  d  e
# a  1  2  3
print(df.iloc[['a']])#报错


#6、ix的单[]。能用行数,也能用索引标签。
print(df.ix[0])
# c    1
# d    2
# e    3
# Name: a, dtype: int64
print(df.ix['a'])
# c    1
# d    2
# e    3
# Name: a, dtype: int64


#7、ix的双[[]]。只能用行数,不能用索引标签。
print(df.ix[[0]])
#    c  d  e
# a  1  2  3
print(df.ix[['a']])#报错


二、分别使用loc、iloc、ix 索引第一列的数据,无双[[]]:

print(df.loc[:,['c']])
#    c
# a  1
# b  4
print(df.iloc[:,[0]])
#    c
# a  1
# b  4
print(df.ix[:,['c']])
#    c
# a  1
# b  4
print(df.ix[:,[0]])
#    c
# a  1
# b  4

三、分别使用loc、iloc、ix 索引多行的数据,无双[[]]:

print(df.loc['a':'b'])
#    c  d  e
# a  1  2  3
# b  4  5  6
print(df.iloc[0:2])
#    c  d  e
# a  1  2  3
# b  4  5  6
print(df.ix['a':'b'])
#    c  d  e
# a  1  2  3
# b  4  5  6
print(df.ix[0:2])
#    c  d  e
# a  1  2  3
# b  4  5  6

四、分别使用loc、iloc、ix 索引多列的数据,无双[[]]:

print(df.loc[:,'c':'d'])
#    c  d
# a  1  2
# b  4  5
print(df.iloc[:,0:2])
#    c  d
# a  1  2
# b  4  5
print(df.ix[:,'c':'d'])
#    c  d
# a  1  2
# b  4  5
print(df.ix[:,0:2])
#    c  d
# a  1  2
# b  4  5

五、常用方式

new_train.loc[new_train['label']==-1,'label']=1
#把new_train这个数据集label一列等于-1的行的label值改为1。一般是与预测集分开。

iloc、loc、ix总结:

1、loc——行(列)标签
iloc——行(列)号
ix——行(列)标签、行(列)号(基于loc和iloc 的混合)

2、索引单行数据可有双[[]],索引单列、多行、多列只有单[];

3、loc的单[]——行(列)标签
loc的双[[]]——行(列)标签、行(列)号
iloc的单[]——行(列)号
iloc的双[[]]——行(列)号
ix的单[]——行(列)标签、行(列)号
ix的双[[]]——行(列)号

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值