Python NumPy Array Indexing Explained - Learn with an Example

  • Context: Python 
  • Thread starter Thread starter EngWiPy
  • Start date Start date
  • Tags Tags
    Array
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 1K views
EngWiPy
Messages
1,361
Reaction score
61
Hello all,

I have this piece of code in Python

Code:
from sklearn.datasets import load_iris

data = load_iris()

features = data['data']
feature_name = data['feature_names']
target = data['target']
target_names = data['target_names']
labels = target_names[target]

print(target.shape)#This outputs (150,)
print(target_names.shape)#This outputs (3,)
print(labels.shape)#This output (150,) but how?

target_names contains 3 elements, how does labels contain 150 elements? How does indexing work in Python's NumPy?

Thanks in advance
 
Physics news on Phys.org
S_David said:
Hello all,

I have this piece of code in Python

Code:
from sklearn.datasets import load_iris

data = load_iris()

features = data['data']
feature_name = data['feature_names']
target = data['target']
target_names = data['target_names']
labels = target_names[target]

print(target.shape)#This outputs (150,)
print(target_names.shape)#This outputs (3,)
print(labels.shape)#This output (150,) but how?

target_names contains 3 elements, how does labels contain 150 elements? How does indexing work in Python's NumPy?

Thanks in advance

This is not a numpy indexing issue.

One tell-tale sign is they did not import numpy anywhere. Another is that your 'data' object has excel style 'column names' being passed to it, which would cause a failure in numpy because numpy only allows numeric indexing.

How much time did you spend reading the sklearn docs? And how much do you know about classification problems in machine learning?

it seems pretty straightforward if you know a little about both and read this page:

http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html