Updating a quickhull implementation to Python 3.2, list manipulation - python

So, I've got a quickhull implementation in python that I'm trying to use in python 3.2. Mostly it's fine, but there's a list indexing problem I'm having. The code does:
axis = sample[:,0]
This doesn't work, as python complains that list indices need to be integers, no tuples. I'm having trouble trying to understand what the line is trying to do. Anyone have any ideas?
Here's some surrounding code, if that helps:
if len(sample) > 2:
axis = sample[:,0]
base = numpy.take(sample, [numpy.argmin(axis), numpy.argmax(axis)], axis=0)
return link(dome(sample, base),
dome(sample, base[::-1]))
else:
return sample
(Additionally, I'm not sure what the base[::-1] means, but that at least works.)

axis is a Python list, but it should be a numpy array. The code is using numpy's special indexing rules for arrays to extract the first column.

Related

Updated Python Starred Expressions Error in Numpy Indexing

I have some code that I have been running in Python 3.6, but when I move to Python 3.9 I recieve the below error:
SyntaxError: can't use starred expression here
I understand some syntax related to expressions of the form (*something) was implemented in 3.9 that is not backwards compatible (see, for example, here).
Here is a minimal working example of what my code tries to do:
# Get some data
y = np.random.randn(100,100,100)
# Indexes stored as a tuple
x = (1,2)
# Result I'm after
result = y[...,(*x)]
In the above example, I am trying to essentially return y[:,1,2], but in practice, my tuple may have more values, and my array may be larger.
The above code works fine in Python 3.6 but doesn't work in Python 3.9. I cannot work out what the equivalent piece of code would be in Python 3.9 and above. I don't want to assume the number of dimensions in Y (e.g. I want to keep the ...), but I want to retain the behaviour I have above. How can I do this?
You were almost there:
result = y[(..., *x)]
Intermediate:
(..., *x)
# (Ellipsis, 1, 2)

Indexing vectors in Matlab

I am used to working with python, and am just getting used to Matlab. I am trying to write a foor loop in Matlab similar to this
x_temp=x[0]
for i in range(0,400):
if x[i]>=x_temp:
x_temp=x[i]
print(x_temp)
I tried
N=401;
x=linspace(-20,20,N);
dt = 0.0002;
t=0:dt:2;
x_temp=x(0);
for j=2: lenght(t)
if x(j)>=x_temp
x_temp=x(j);
end
end
print(x_temp);
but I get an error saying 'Array indices must be positive integers or logical values.' Could anyone please help answer how I should index the vectors properly in matlab?
Arrays start at 1 in matlab, not 0 like in python. It's kind of a pain but you'll get used to it.
It's not really clear what you are trying to compute here since it's just a fragment, but it looks like you want the largest element in the array. No need for a for loop, just use the max function on the subset of the array you want to test:
[value, index] = max( x(2:length(t)) ) ;
In general what makes matlab better than other languages for math/science is the powerful built in functions. Never write a for loop before you check if there's a simple function or one-line vector operation that gives the same result (and in most cases, much quicker).

Python only printing last element of the list

I am a Python newbie using Jupyter Notebook, and I am coming across the following problem:
I create 2 very simple lists and assign them to their own respective variables, which works fine.
My code is below:
x = [-2,1,3]
y = [-1,1,2]
I then execute other pieces of simple code, which involves using Matplotlib to plot a graph with values from the lists and also multiplying each element in the lists.
However, I noticed when I try to print the original lists after initialising them, I only get the last element from the list as an integer, not in list form. I find this strange as I haven't made any changes to the lists.
The issue isn't prominent, because I'm still able to continue to use the lists in their original form e.g. to plot the graph, but I'm wondering why this is happening, hoping to strengthen my Python/programming knowledge...
I've added screenshots to display my issue more clearly, but please ask me to explain anything if I haven't made myself clear.
Thanks in advance everyone!!
I think there is an issue in your output of Jupyter, because you pass from the line 93 to 88 and between we don't see the instructions you used.
I might be wrong , but your problem is that you are giving the same name for both the iterator and the sequence in line 85. instead of doing this:
xy = [x*y for x,y in zip(x,y)]
try this:
xy = [i*j for i,j in zip(x,y)]

Convert numpy.ndarray to list (Python)

I am running a function developed by Esri to get list of values in a integer column of a spatial table (however, the same behaviour is observed even when running the function on a non-spatial table). According to the help, I should get NumPy structured array. After running the function, I have a numpy array. I run print in this format:
in_table = r"C:\geodb101#server.sde\DataTable" #
data = arcpy.da.TableToNumPyArray(in_table, "Field3")
print data
Which gives me back this in IDE (copy/pasted from IDE interpreter):
[(20130825,) (20130827,) (20130102,)]
I am running:
allvalues = data.tolist()
and getting:
[(20130825,), (20130827,), (20130102,)]
Same result when running data.reshape(len(data)).tolist() as suggested in comments.
Running type() lets me know that in the first case it is <type 'numpy.ndarray'> and in the second case <type 'list'>. I am expecting to get my output list in another format [20130825, 20130827, 20130102]. What am I doing wrong or what else should I do to get the output list in the specified format?
I have a possible approach, but I'm not 100% sure it will work, as I can't figure out how you got tuples into an array (when I tried to create an array of tuples, it looks like the tuples got converted to arrays). In any case, give this a shot:
my_list = map(lambda x: x[0], my_np_array_with_tuples_in_it)
This assumes you're dealing specifically with the single element tuples you describe above. And like I said, when I tried to recreate your circumstances, numpy did some conversion moves that I don't fully understand (not really a numpy expert).
Hope that helps.
Update: Just saw the new edits. Not sure if my answer applies anymore.
Update 2: Glad that worked, here's a bit of elaboration.
Lambda is basically just an inline function, and is a construct common in a lot of languages. It's essentially a temporary, anonymous function. You could have just as easily done something like this:
def my_main_func():
def extract_tuple_value(tup):
return tup[0]
my_list = map(extract_tuple_value, my_np_array_with_tuples_in_it)
But as you can see, the lambda version is more concise. The "x" in my initial example is the equivalent of "tup" in the more verbose example.
Lambda expressions are generally limited to very simple operations, basically one line of logic, which is what is returned (there is no explicit return statement).
Update 3: After chatting with a buddy and doing some research, list comprehension is definitely the way to go (see Python List Comprehension Vs. Map).
From acushner's comment below, you can definitely go with this instead:
my_list = [tup[0] for tup in my_np_array_with_tuples_in_it]

unknown vector size python

I have a matlab code that I'm trying to translate in python.
I'm new on python but I have been able to answer a lot of questions googling a little bit.
But now, I'm trying to figure out the following:
I have a for loop when I apply different things on each column, but you don't know the number of columns. For example.
In matlab, nothing easier than this:
for n = 1:size(x,2); y(n) = mean(x(:,n)); end
But I have no idea how to do it on python when, for example, the number of columns is 1, because I can't do x[:,1] in python.
Any idea?
Thanx
Yes, if you use numpy you can use x[:,1], and also you get other data structures (vectors instead of lists), the main difference between matlab and numpy is that matlab uses matrices for calculations and numpy uses vectors, but you get used to it, I think this guide will help you out.
Try numpy. It is a python bindings for high-performance math library written in C. I believe it has the same concepts of matrix slice operations, and it is significantly faster than the same code written in pure python (in most cases).
Regarding your example, I think the closest would be something using numpy.mean.
In pure python it is hard to calculate mean of column, but it you are able to transpose the matrix you could do it using something like this:
# there are no builtin avg function
def avg(lst):
return sum(lst)/len(lst)
rows = list(avg(row) for row in a)
this is one way to do it
from numpy import *
x=matrix([[1,2,3],[2,3,4]])
[mean(x[:,n]) for n in range(shape(x)[1])]
# [1.5, 2.5, 3.5]

Categories

Resources