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



