I get NameError: name 'array' is not defined in python error when I want to create array, for example:
a = array([1,8,3])
What am I doing wrong? How to use arrays?
You need to import the array method from the module.
from array import array
http://docs.python.org/library/array.html
For basic Python, you should just use a list (as others have already noted).
If you are trying to use NumPy and you want a NumPy array:
import numpy as np
a = np.array([1,8,3])
If you don't know what NumPy is, you probably just want the list.
If you need a container to hold a bunch of things, then lists might be your best bet:
a = [1,8,3]
Type
dir([])
from a Python interpreter to see the methods that lists support, such as append, pop, reverse, and sort.
Lists also support list comprehensions and Python's iterable interface:
for x in a:
print x
y = [x ** 2 for x in a]
You probably don't want an array. Try using a list:
a = [1,8,3]
Python lists perform like dynamic arrays in many other languages.
You need to import the array.
from numpy import array
In python Import problem occurs when you accidentally name your working file the same as the module name. This way the python opens the same file you created using the same as module name which causes a circular loop and eventually throws an error.
This question is asked 10 yrs ago , but it may be helpful for late python learners
If you're trying to use NumPy, use this:
import numpy as np
a = np.array([1, 2, 3])
If not then a list is way more easier:
a = [1, 2, 3]
**from array import ***
myarray=array('i',[10,39,48,38])
Maybe you havenĀ“t executed the cell. It worked for me
enter image description here
Related
The snippet below is supposed to take in image labels(directory consists of respective labels as file names) in the given directory and plot the image using a subplot.
import os
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
training_hor_dir='./horse-or-human/horses'
training_hum_dir='./horse-or-human/humans'
nrows=4
ncols=4
pic_index=0
fig=plt.gcf()
fig.set_size_inches(ncols*4,nrows*4)
pic_index+=8
next_horse_pic=[os.path.join(training_hor_dir,fname)
for fname in training_hor_labels[pic_index-8:pic_index]]
Can someone please walk me through how the following for loop work? What's the core concept behind such a snippet(join statement followed by for loop inside an array ? I can't get my head around it)?
Also, Is it possible to add in furthermore statements after for loop? If so, how? and if not, why?
And how to print fname inside for-loop?
Any help is appreciated. Thanks in advance.
It's called a comprehension: it's a clever way of creating new data from data you already have. Generally it works like this:
newList = [oldValue * 2 for oldValue in oldList]
Where oldValue * 2 can be replaced with whatever operation you want.
There's lots of other things you can do with comprehensions - too much to list here. Dictionaries, nested comprehensions, and so on. Here's an article to get started.
As for printing (or executing any commands for that matter) technically you can just throw away the new value, like so:
uselessList = [print(item) for item in oldList]
But then the new uselessList would just be loads of Nones. What I'd do is just use another for loop and print the items out the old fashioned way.
This question already has answers here:
Is there a NumPy function to return the first index of something in an array?
(20 answers)
Closed 3 years ago.
I want to ask a question about finding the position of an element within an array in Python's numpy package.
I am using Jupyter Notebook for Python 3 and have the following code illustrated below:
concentration_list = array([172.95, 173.97, 208.95])
and I want to write a block of code that would be able to return the position of an element within the array.
For this purpose, I wanted to use 172.95 to demonstrate.
Initially, I attempted to use .index(), passing in 172.95 inside the parentheses but this did not work as numpy does not recognise the .index() method -
concentration_position = concentration_list.index(172.95)
AttributeError: 'numpy.ndarray' object has no attribute 'index'
The Sci.py documentation did not mention anything about such a method being available when I accessed the site.
Is there any function available (that I may not have discovered) to solve the problem?
You can go through the where function from the numpy library
import numpy as np
concentration_list = np.array([172.95, 173.97, 208.95])
number = 172.95
print(np.where(concentration_list == number)[0])
Output : [0]
Use np.where(...) for this purpose e.g.
import numpy as np
concentration_list = np.array([172.95, 173.97, 208.95])
index=np.ravel(np.asarray(concentration_list==172.95).nonzero())
print(index)
#outputs (array of all indexes matching the condition):
>> [0]
My code currently has an array, lets say for example:
arr = np.ones((512, 512)).
There is an area of the array that interests me. I usually access it like this:
arr[50:200,150:350] #do stuff here.
I was wondering, is there some way to make a variable that holds [50:200,150:350]? This way, if I need to slightly change my mask, I can do it once, on the top of the file, instead of everywhere it is accessed.
I tried mask = [50:200,150:350], arr[mask] but Python syntax won't allow that.
Thanks for the help!
Apparently numpy extends slicing and allows multiple slice() objects, one per dimension.
import numpy
o = numpy.ones((32, 32))
print(o[3:5,3:5])
foo = slice(3,5), slice(3,5)
print(o[foo])
Both incantations produce same result :)
I'm pretty new to Python numpy. I was attempted to use numpy array as the key in dictionary in one of my functions and then been told by Python interpreter that numpy array is not hashable. I've just found out that one way to work this issue around is to use repr() function to convert numpy array to a string but it seems very expensive. Is there any better way to achieve same effect?
Update: I could create a new class to contain the numpy array, which seems to be right way to achieve what I want. Just wondering if there is any better method?
update 2: Using a class to contain data in the array and then override __hash__ function is acceptable, however, I'd prefer the solution provided by #hpaulj. Convert the array/list to a tuple fits my need in a better way as it does not require an additional class.
If you want to quickly store a numpy.ndarray as a key in a dictionary, a fast option is to use ndarray.tobytes() which will return a raw python bytes string which is immutable
my_array = numpy.arange(4).reshape((2,2))
my_dict = {}
my_dict[my_array.tobytes()] = None
After done some researches and reading through all comments. I think I've known the answer to my own question so I'd just write them down.
Write a class to contain the data in the array and then override __hash__ function to amend the way how it is hashed as mentioned by ZdaR
Convert this array to a tuple, which makes the list hashable instantaneously.Thanks to hpaulj
I'd prefer method No.2 because it fits my need better, as well as simpler. However, using a class might bring some additional benefits so it could also be useful.
I just ran into that issue and there's a very simple solution to it using list comprehension:
import numpy as np
dict = {'key1':1, 'key2':2}
my_array = np.array(['key1', 'key2'])
result = np.array( [dict[element] for element in my_array] )
print(result)
The result should be:
[1 2]
I don't know how efficient this is but seems like a very practical and straight-forward solution, no conversions or new classes needed :)
I have this code where I want to reference all elements of m in matlab:
NNanm = sum(isnan(m(:)));
How would I tell python to reference all the elements of m?
If I understand your code correctly, you count all nan elements in the matrix. If so, you can do the equivalent thing in python this using numpy with the following code:
import numpy as np
np.count_nonzero(np.isnan(m))
If you insist on the sum function, this also work:
np.sum(np.isnan(m))