Python – what is this syntax? my_2d_list[0:20,1]

Question:

Having a tough time googling or fiddling around with the interpreter to find out what this thing is inside the brackets. Here’s the code in context:

    from matplotlib.mlab import PCA as mlabPCA

    mlab_pca = mlabPCA(all_samples.T)

    print('PC axes in terms of the measurement axes'
            ' scaled by the standard deviations:n',
              mlab_pca.Wt)

    plt.plot(mlab_pca.Y[0:20,0],mlab_pca.Y[0:20,1], 'o', markersize=7,
            color='blue', alpha=0.5, label='class1')
    plt.plot(mlab_pca.Y[20:40,0], mlab_pca.Y[20:40,1], '^', markersize=7,
            color='red', alpha=0.5, label='class2')

    plt.xlabel('x_values')
    plt.ylabel('y_values')
    plt.xlim([-4,4])
    plt.ylim([-4,4])
    plt.legend()
    plt.title('Transformed samples with class labels from matplotlib.mlab.PCA()')

    plt.show()

I tried making a little 2d array like

    a = [[1,2],[1,2],[1,2],[1,2],[1,2]]

and evaluating

    a[0:2,0]

But that doesn’t give me anything. Thanks!

Code taken from http://sebastianraschka.com/Articles/2014_pca_step_by_step.html in the “Using the PCA() class from the matplotlib.mlab library” section.

Asked By: Josh Lemer

||

Answers:

Native python lists (what you’re creating for a above) do not support indexing or slicing, at least the way you’re doing it. There are two solutions going forward:

  1. Use numpy

To access indexes and slices, you can use the syntax as you’re already using it.

import numpy as np
a = np.array([[1,2],[1,2],[1,2],[1,2],[1,2]])
a[0:2, 0] # returns array([1, 1])
  1. Access your native python list with a different syntax.

Note this method does not actually allow slicing the way you’re using it above. But, you can do: a[0][1] instead of a[0, 1] with a list to correctly access the 0, 1 element. But again, no slicing (a[0:2][0] will produce some undesired results).

Seems like you might be coming from Matlab, just based on a few syntactic choices. If so, use this great reference guide to ease the transition: Link

Answered By: tyleha
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.