2017 答案 - 熊猫 0.20:.ix 已弃用。使用 .loc
请参阅文档中的弃用
.loc
使用基于标签的索引来选择行和列。标签是索引或列的值。切片.loc
包含最后一个元素。
假设我们有一个包含以下列的 DataFrame:
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