栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在pandas中获取数据框的列切片

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在pandas中获取数据框的列切片

2017年答案-熊猫0.20:.ix已弃用。使用.loc

请参阅文档中的弃用

.loc
使用基于标签的索引来选择行和列。标签是索引或列的值。切片
.loc
包含最后一个元素。

假设我们有以下的列的数据框中:

foo
bar
quz
ant
cat
sat
dat

# selects all rows and all columns beginning at 'foo' up to and including 'sat'df.loc[:, 'foo':'sat']# foo bar quz ant cat sat

.loc
接受与Python列表对行和列所做的相同的切片表示法。切片符号为
start:stop:step

# slice from 'foo' to 'cat' by every 2nd columndf.loc[:, 'foo':'cat':2]# foo quz cat# slice from the beginning to 'bar'df.loc[:, :'bar']# foo bar# slice from 'quz' to the end by 3df.loc[:, 'quz'::3]# quz sat# attempt from 'sat' to 'bar'df.loc[:, 'sat':'bar']# no columns returned# slice from 'sat' to 'bar'df.loc[:, 'sat':'bar':-1]sat cat ant quz bar# slice notation is syntatic sugar for the slice function# slice from 'quz' to the end by 2 with slice functiondf.loc[:, slice('quz',None, 2)]# quz cat dat# select specific columns with a list# select columns foo, bar and datdf.loc[:, ['foo','bar','dat']]# foo bar dat

您可以按行和列进行切片。举例来说,如果你有5列的标签

v
w
x
y
z

# slice from 'w' to 'y' and 'foo' to 'ant' by 3df.loc['w':'y', 'foo':'ant':3]#    foo ant# w# x# y


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/640351.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号