pandas数据索引:loc、iloc和ix

本文介绍了pandas中数据索引的方法,包括loc通过行标签获取数据,如loc['d']用于获取指定行;以及iloc通过行号获取数据,如iloc[1]用于获取第一行。Python3已不再推荐使用ix混合索引。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、loc

通过行标签索引行数据

 (1)、loc[‘d’]:获取第’d’行数据

import pandas as pd  
data = [[1,2,3],[4,5,6]]  
index = [‘d’,'e']  
columns=['a','b','c']  
df = pd.DataFrame(data=data, index=index, columns=columns)  
print(df.loc['e']) 
a    4
b    5
c    6
Name: 1, dtype: int64
(2)、loc['d':]获取第‘d’行及之后的多行数据
import pandas as pd  
data = [[1,2,3],[4,5,6]]  
index = ['d','e']  
columns=['a','b','c']  
df = pd.DataFrame(data=data, index=index, columns=columns)  
print(df.loc['d':])
   a  b  c
d  1  2  3
e  4  5  6
(3)、loc['d',['b']]索引第‘d’行第‘b’列

import pandas as pd  
data = [[1,2,3],[4,5,6]]  
index = ['d','e']  
columns=['a','b','c']  
df = pd.DataFrame(data=data, index=index, columns=columns)  
print(df.loc['d',['b']])
b    2
Name: d, dtype: int64
通过df.[列标签]可直接获取某列数据,但当标签未知时可通过这种方式获取列数据

2、iloc

通过行号获取行数据

(1)、iloc[1]获取第1行数据

import pandas as pd  
data = [[1,2,3],[4,5,6]]  
index = ['d','e']  
columns=['a','b','c']  
df = pd.DataFrame(data=data, index=index, columns=columns)  
print(df.iloc[1]) 
a    4
b    5
c    6
Name: e, dtype: int64
(2)、iloc[0:]获取第0行及之后的多行数据

import pandas as pd  
data = [[1,2,3],[4,5,6]]  
index = ['d','e']  
columns=['a','b','c']  
df = pd.DataFrame(data=data, index=index, columns=columns)  
print(df.iloc[0:])
   a  b  c
d  1  2  3
e  4  5  6
(3)、iloc[:,[1]]获取第1列数据
import pandas as pd  
data = [[1,2,3],[4,5,6]]  
index = ['d','e']  
columns=['a','b','c']  
df = pd.DataFrame(data=data, index=index, columns=columns)  
print(df.iloc[:,[1]])
   b
d  2
e  5
3、ix

前两种的混合索引,Python3已经不使用这种索引方式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值