I have a numpy array of floats that I want to reassign with a different value using a for loop but PyCharm says the new variable assignment isn't being used.
If I have, say:
for i in array:
i = i * 5
It will say that i is an unused variable. What am I doing wrong?
You need to assign values to array elements. Otherwise you array will remain unchanged. There are a couple of ways.
Using your current attempt as a starting point, you can use enumerate. Given an input array:
for idx, val in enumerate(array):
array[idx] = val * 5
But this doesn't take advantage of NumPy vectorisation. You can simply use:
array *= 5
Should be:
for i in range(len(array)):
array[i] = array[i] * 5
What you did was creating a temporary variable "i", which exists only on each loop iteration, it is initialized with the value of an element from the list and then it's deleted.
A more pythonic way of doing this would be:
array = [i*5 for i in array]
Related
I am pretty new to python, i am using python 3 and have some difficulties to append the result of the iteration to the array, following is my chunk of my code:
A = np.random.randn(len(meas),numx)
lengthA = np.linspace(0,len(A[0])-1,num=len(A[0]),dtype=int)
anorm = []
for j in range(0,len(lengthA)):
x_normed = A/A.max(axis=0)
anorm[:,j] = A[:,j]*x_normed[j]
Is it necessary to append the new result to empty anom ? somehow the code always tell me that the list of the indices must be integer and not tuple. Any help will be appreciated.
When assigning a value to an array at index n via the array[index] = value syntax, the argument within the square brackets must be an integer. In your situation, j is an integer but [:,j] attempts to reference multiple indices within the array.
for j in range(0,len(lengthA)):
x_normed = A/A.max(axis=0)
anorm[j] = A[:,j]*x_normed[j]
As an aside, if you want your for loop to run for as many iterations as there are elements within lengthA, then you can simply do:
for j in lengthA:
do stuff
I'm having some trouble understanding how nested single line for loops work. Here's an example:
I have this code:
NewArray = np.array([ get_position(i, size-1, t) for i in range(0, size)])
and I'm trying to rewrite this to:
for i in range(0,size):
NewArray = np.array([ get_position(i, size-1, t)])
But I'm getting different outputs, so I'm guessing there's a logic error here.
Could you point out the issue?
Thank you
It's because the first one creates a numpy array containing all your values (you create all values because you're using a list comprehension) and the second one creates a new array containing the last value each iteration (and it discards the array created in the last iteration because you reuse the same name).
You could rewrite the second one as:
lst = []
for i in range(0,size):
lst.append(get_position(i, size-1, t))
NewArray = np.array(lst)
that should give the same result as your first operation.
In the first you create an array of length size.
In the second you repeatedly (size times) create an array of length 1.
I'm trying to create a bidimensional array using list comprehension.
a = [[0 for y in range(1, 10)] for x in range(1, 10)]
This should create a 9x9 'matrix' whose first item is a[1][1], and last is a[9][9]
However this is not happening, and when I try to print the last element:
print(a[9][9])
I get an out of range error.
What am I doing wrong?
You do have a 9x9 matrix (or list of lists), but since indices are zero based, you can only index from 0 to 8 along both axes.
The start value 1 in the range function does not influence the start value of your indexing; it will always be zero.
I have a list called L. It has C number of elements.
I have a nd array called X. X has Boolean data (either 0 or 1). It has dimension as (20,C). There are 20 lists with each list having C number of elements
I want to locate each index that has value of 1 in X.Then I want the value at this same index in List L, and finally store this value from L in another nd array .
I write the following code
emptylist=[]
for index,value in np.ndenumerate(X): #this index is a tuple like (0,3)
tuple_to_list=list(i)
if value == 1:
emptylist.append (L[tuple_to_list[1]]) #error
the program does not stop running. Can you guide me to improve this code ?
the last line should be:
empylist.append(L[index[0]])
and I don't see what your tuple_to_list is needed for
A solution using only arrays would be the following:
L = list(np.random.rand(20)) # gives a List of radom values (to be compatible to the question)
La = np.array(L)
X = randint(0,5,(20,101)) # make an array having values from 0...4
emptylist = La[np.where(X==1)[0]] #gives those rows of L where rows of X contain 1
though the name empty is not appropriate anymore.
How do you alternatively append or overwrite a list element in python?
I am currently trying to translate a function I have working in ruby to python, my ruby code looks like such:
def self.push_array_hash(key,selector,level,array)
(0..array.length).each do |i|
x = array[i]
selector[level] = i+1
if(x.is_a?(Array))
self.push_array_hash(key,selector,level+1,x)
end
self.push_datum("#{key}(#{selector.join(',')})", x)
end
end
I am able to call this function as: self.push_array_hash(key,Array.new,0,val) without having to know the dimensions of the nested arrays. The code selector[level] = i+1 easily handles appending an element to the array if selector[level] does not exist yet, and changing the value at level if it does exist.
That is ruby (only given so everyone can understand the what I am aiming for), on to python. Here is my translated code:
def push_list_dict(self, key, selector, level, array):
for i, x in enumerate(array):
selector[level] = i+1
if isinstance(x, (list, set)):
if isinstance(value, set):
value = sorted(value)
self.push_list_dict(key,selector,level+1,x)
self.push_datum(key+"("+",".join(map(str, selector))+")",x)
I call the function as such: self.push_array_dict(key,[],0,value), however it breaks on selector[level] = i+1 and gives me the error: IndexError: list assignment index out of range. Is there an easy way of alternatively appending a value to the array or resetting the value? Thanks,
Joshua
You could use:
selector[level:level+1] = [i+1]
If selector[level] already exists, this replaces the value.
If it does not already exist, it appends the value.
For example,
In [102]: selector = []
In [103]: selector[0:1] = [100]
In [104]: selector
Out[104]: [100]
In [105]: selector[0:1] = [200]
In [106]: selector
Out[106]: [200]
Notice what happens if the index is beyond the length of selector:
In [107]: selector[7:8] = [300]
In [108]: selector
Out[108]: [200, 300]
It does not insert at that index location, it just appends.
Python doesn't magically extend the array the way ruby does. One way is to check the length and pad to the correct length using [None] * x or [0] * x
selector += [None] * (level-len(selector))
selector[level] = i+1
Aside:
range doesn't include the "stop" value, so you may not want the -1 there. The usual way to write this
for i in range(0,len(array)-1):
x = array[i]
...
is
for i, x in enumerate(array):
...