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 column
df.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 3
df.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 function
df.loc[:, slice('quz',None, 2)]
# quz cat dat
# select specific columns with a list
# select columns foo, bar and dat
df.loc[:, ['foo','bar','dat']]
# foo bar dat
您可以按行和列进行切片。举例来说,如果你有5列的标签v
,w
,x
,y
,z
# slice from 'w' to 'y' and 'foo' to 'ant' by 3
df.loc['w':'y', 'foo':'ant':3]
# foo ant
# w
# x
# y
df[5:10]
添加了选择行(pandas.pydata.org/pandas-docs/stable/...)