我可以看到有2/3种索引方式。 iloc,loc和ix(我猜是在较早的版本中)。在进行实验时,我发现了另一种可行的方法。想要澄清,为什么行得通?当用户未指定任何内容时,loc是默认方法吗?
import pandas as pd
import seaborn as sns
iris = sns.load_dataset("iris")
iris[iris['species']=="setosa"].head()
和
iris.loc[iris.species == "setosa"].head()
得到的结果与
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 4.6 3.1 1.5 0.2 setosa
4 5.0 3.6 1.4 0.2 setosa
我检查的虹膜类型也是pandas.core.frame.DataFrame
答案 0 :(得分:1)
由于loc
与布尔序列或布尔数组一起使用,因此这两个结果相同。
因此,当您给出布尔级数(iris['species']=="setosa")
(iris['species']=="setosa")
0 True
1 True
2 True
3 True
4 True
...
145 False
146 False
147 False
148 False
149 False
Name: species, Length: 150, dtype: bool
(iris[iris['species']=="setosa"]
和iris.loc[iris.species == "setosa"]
)都在做boolean indexing。
iloc
,works only with a Boolean array时,要在同一掩码下使用iloc
,可以将布尔级数传递给numpy数组:
iris.iloc[(iris['species']=="setosa").values].head()