pandas中如何选取某几列_【python】pandas中 loc amp; iloc用法及区别
生活随笔
收集整理的这篇文章主要介绍了
pandas中如何选取某几列_【python】pandas中 loc amp; iloc用法及区别
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
在刚学习Python的时候,对于loc、iloc、at、iat、ix有点混乱,没有进行过整理和梳理。所以针对这几种用法进行一次案例的整理。本次优先整理loc和iloc
SQL中的select是根据列的名称来选取;Pandas则更为灵活,不但可根据列名称选取,还可以根据列所在的position(数字,在第几行第几列,注意pandas行列的position是从0开始)选取。相关函数如下:
1)loc:通过标签或布尔数组获得一组行和列。
2)iloc:通过整数位置获得行和列的数据。
一、loc :通过标签或布尔数组获得一组行和列。
2-1先定义一个DataFrame:import pandas as pd df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],index=['cobra', 'viper', 'sidewinder'],columns=['max_speed', 'shield'])DataFrame结果:
max_speed shield cobra 1 2 viper 4 5 sidewinder 7 82-2.loc选定index标签,获取某一行,.loc[],中括号里面是先行后列,以逗号分割,行和列分别是行标签和列标签1、通过行名称获取整行数据:
获得'cobra'所在的行:
df.loc['viper']执行结果:
max_speed 1 shield 22、通过行名称,列名称定位数据:
df.loc['cobra', 'shield']执行结果:
23、通过切片行标签和单个标签列,获取一组数据:
df.loc['cobra':'viper', 'max_speed']执行结果:
cobra 1 viper 44、通过条件筛选数据:
#先筛选到'shield'这一列大于6所在的数据,并且筛选出对应的这几行 df.loc[df['shield'] > 6]执行结果:
max_speed shield sidewinder 7 8二、iloc :通过整数位置获得行和列的数据。
3-1先定义一个DataFrameimport pandas as pd df = pd.DataFrame([[1,2,3,4], [100,200,300,400], [1000,2000,3000,4000]],columns=['a', 'b','c','d'])DataFrame结果:
a b c d 0 1 2 3 4 1 100 200 300 400 2 1000 2000 3000 40001、通过行索引获取数据
#获取index 为0 所在的行数据 df.iloc[0]执行结果:
a 1 b 2 c 3 d 42、通过行索引获取多行数据
df.iloc[[0, 1]]执行结果:
a b c d 0 1 2 3 4 1 100 200 300 4003、通过切片index来获取数据
df.iloc[:3]执行结果:
a b c d 0 1 2 3 4 1 100 200 300 400 2 1000 2000 3000 40004、通过切片行和列来获取一组数据
#iloc[]中先行后列,同loc df.iloc[1:3, 0:3]执行结果:
a b c 1 100 200 300 2 1000 2000 3000三、总结
关于iloc和loc先总总结到这里,如果有疑问的小伙伴欢迎留言或者私信。
总结
以上是生活随笔为你收集整理的pandas中如何选取某几列_【python】pandas中 loc amp; iloc用法及区别的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 一加Nord 3再曝新料 1.5K屏不太
- 下一篇: python 取一个字前的文本的_pyt