Pandas中的选择
1.选择
更多细节可见官方文档
import pandas as pd
ID = [1,2,3]
Name = ['Student_001','Student_002','Student_003']
Age = [16,26,33]
Score = [87,92,100]
# 自定义的索引名称
index = ['x','y','z']
df = pd.DataFrame({'ID':ID,'Name':Name,'Age':Age,'Score':Score})
自定义索引 | ID | Name | Age | AgeScore |
---|---|---|---|---|
x | 1 | Student_001 | 16 | 87 |
y | 2 | Student_002 | 26 | 92 |
z | 3 | Student_003 | 33 | 100 |
1.1单个值的选择
df.at[ ]
Similar to loc
, in that both provide label-based lookups. Use at
if you only need to get or set a single value in a DataFrame or Series.
和 loc 类似,都是使用标签(即名称<自己命名的字符>)进行索引
at = df.at['x','ID']
# 或at = df['ID'].at['x']
out:1
df.iat[ ]
Similar to iloc
, in that both provide integer-based lookups. Useiat
if you only need to get or set a single value in a DataFrame or Series.
和 iloc 类似,都是基于整数进行索引,即 [0-length-1]
iat = df.iat[0,0] #0行0列,从0开始;类似于线性代数的矩阵
# 或iat = df['ID'],iat[0]
out:1
1.2整行 (row) 和整列 (column) 的选择
df.loc[row(名称),column(名称) ]
Access a group of rows and columns by label(s) or a boolean array. .loc[]
is primarily label based, but may also be used with a boolean array.
注意:通过标签(label)进行索引
loc = df.loc[:,'Age'] #选择Age整列,结果以Series的形式显示
df.iloc[ row,column]
.iloc[]
is primarily integer position based (from 0
tolength-1
of the axis), but may also be used with a boolean array.
row 和column 的值均为 [0~length-1]
iloc = df.iloc[:,2] #选择Age整列
结果均为下图形式:
PS:关于 df.ix[ ]
的说明:在 pandas 的 1.0.0 版本开始,移除了 Series.ix and DataFrame.ix 方法使用 DataFrame 的 loc 方法或者iloc 方法进行替换!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律