pandas-DataFrame通过标签索引loc和位置索引 iloc获取数据

本文介绍如何利用pandas库中的DataFrame结构,通过标签索引loc和位置索引iloc有效地获取数据。通过具体代码示例,详细解释了这两种方法在数据检索中的应用。

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

代码示例:

import pandas as pd

df = pd.read_csv('test.csv')
print(df)
'''
打印:
   userId  score  age
0       1     45   18
1       2     65   19
2       3     58   17
3       4     92   16
4       5     78   18
'''

'''
df.loc[]  通过标签索引获取数据
df.iloc[] 通过位置索引获取数据
'''

df.index = list("qwert")
print(df.loc['w','age'])    #打印:19
print(df.loc['w']) 
print(df.loc['w',:]) 
'''
以上两个均为打印一行,类型为Series结果如下:
userId     2
score     65
age       19
Name: w, dtype: int64
'''
print(df.loc[['w','r']])
print(df.loc[['w','r'],:])
'''
以上两个均为打印一行,类型为DataFrame,结果如下:
   userId  score  age
w       2     65   19
r       4     92   16
'''
print(df.loc[['w','r'],['userId','score']])
'''
获取多行多列,打印&
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值