I’m a Matlab user needing to use Python for some things, I would really appreciate it if someone can help me out with Python syntax:
(1) Is it true that lists can be indexed by tuples in Python? If so, how do I do this? For example, I would like to use that to represent a matrix of data.
(2) Assuming I can use a list indexed by tuples, say, data[(row,col)], how do I remove an entire column? I know in Matlab, I can do something like
new_data = [data(:,1:x-1) data(:,x+1:end)];
if I wanted to remove column x from data.
(3) How can I easily count the number of non-negative elements in each row. For example, in Matlab, I can do something like this:
sum(data>=0,1)
this would give me a column vector that represents the number of non-negative entries in each row.
Thanks a lot!
I agree with everyone. Use Numpy/Scipy. But here are specific answers to your questions.
Yes. And the index can either be a built-in list or a Numpy array. Suppose
x = scipy.array([10, 11, 12, 13])andy = scipy.array([0, 2]). Thenx[[0, 2]]andx[y]both return the same thing.new_data = scipy.delete(data, x, axis=0)(data>=0).sum(axis=1)Careful: Example 2 illustrates a common pitfall with Numpy/Scipy. As shown in Example 3, the
axisproperty is usually set to 0 to operate along the first dimension of an array, 1 to operate along the second dimension, and so on. But some commands likedeleteactually reverse the order of dimensions as shown in Example 2. You know, row major vs. column major.