新手问题:为什么建立索引?

问题描述 投票:0回答:1

我正在尝试仅提取scikit learning的虹膜数据集中的杂色花瓣长度条目。这对应于第50到99行。我一直被告知python索引排除了最后一个条目,即1:10是从1到9的所有数字。

因此,为什么以下命令包含第99行?这个包容性的索引(包括最终值)仅仅是带有loc的熊猫吗?我的代码在下面并且可以工作,但是我不知道为什么,我的直觉是将loc中的索引设置为[50:100]

from sklearn import datasets
import pandas as pd
import numpy as np
iris = datasets.load_iris() #load iris
iris_df=pd.DataFrame(data= np.c_[iris['data'], iris['target']],
                     columns= iris['feature_names'] + ['target']) #convert iris to dataframe
versicolor_petal_length=iris_df.loc[50:99,['petal length (cm)']] #extract rows 50-99 of petal length (cm) column
print(versicolor_petal_length)

输出包括第99行,

    petal length (cm)
50                4.7
51                4.5
52                4.9
53                4.0
54                4.6
55                4.5
56                4.7
57                3.3
58                4.6
59                3.9
60                3.5
61                4.2
62                4.0
63                4.7
64                3.6
65                4.4
66                4.5
67                4.1
68                4.5
69                3.9
70                4.8
71                4.0
72                4.9
73                4.7
74                4.3
75                4.4
76                4.8
77                5.0
78                4.5
79                3.5
80                3.8
81                3.7
82                3.9
83                5.1
84                4.5
85                4.5
86                4.7
87                4.4
88                4.1
89                4.0
90                4.4
91                4.6
92                4.0
93                3.3
94                4.2
95                4.2
96                4.2
97                4.3
98                3.0
99                4.1

鉴于此,有人可以向我解释,何时索引将包含最后一个元素,何时索引将排除它?我对此有一些麻烦。

谢谢

pandas indexing scikit-learn
1个回答
1
投票

[我相信您正在考虑属于Numpy库的np.arange(不包括最后的索引,如here所示),而df.loc来自Pandas库,并且包含所有wrt索引,如示例here所示。

© www.soinside.com 2019 - 2024. All rights reserved.