假设我们有以下 DataFrame data
:
petal_length petal_width class
0 1.4 0.2 SETOSA
1 4.7 1.4 VERSICOLOR
2 5.1 1.5 VERSICOLOR
3 6.3 2.5 VIRGINICA
4 1.5 0.3 SETOSA
我们希望选取 class
列等于 'SETOSA'
的数据的 'petal_length'
列。可以使用布尔索引来完成:
iris_type = 'SETOSA'
selected_data = data['petal_length'][data['class'] == iris_type]
在这个例子中,data['class'] == iris_type
返回的布尔数组是 [True, False, False, False, True]
就很自然把其他的给去掉了