I want to understand why the comportement of my array is like that:
import numpy as np
import math
n=10
P=np.array([[0]*n]*n)
P[2][2]=1 #It works as I want
for i in range(n):
for j in range(n):
P[i][j]=math.comb(n,j+1)*((i+1)/n)**(j+1)*(1-(i+1)/n)**(n-j-1)
print(math.comb(n,j+1)*((i+1)/n)**(j+1)*(1-(i+1)/n)**(n-j-1))
print(P)
I get as a result for P an array with only 0 except 1 for the (n,n) position but values printed are not 0.
I suppose it comes from the fact that I use [[0]*n]*n for my list with mutable/immutable variable because it works well when I use np.zeros() but I don't understand why it works when I set value manually (with P[2][2]=1 for example)
Thanks
The way you are creating the array is defaulting to an integer dtype because it uses the first value to determine the type if you don't explicitly set it. You can demonstrate this by trying to assign a float instead of an int with
P[2][2]=1 #It works as I want
P[2][2]=0.3 #It doesn't work
To use your approach you need to create an array with a dtype of float so values don't get clipped: P=np.array([[0.0]*n]*n) or P=np.array([[0]*n]*n, dtype=float).
This will produce an array of the expected values:
array([[3.87420489e-01, 1.93710245e-01, 5.73956280e-02, 1.11602610e-02,
1.48803480e-03, 1.37781000e-04, 8.74800000e-06, 3.64500000e-07,
9.00000000e-09, 1.00000000e-10],
[2.68435456e-01, 3.01989888e-01, 2.01326592e-01, 8.80803840e-02,
2.64241152e-02, 5.50502400e-03, 7.86432000e-04, 7.37280000e-05,
4.09600000e-06, 1.02400000e-07],
...
Related
As the title says I want to make a numpy array.
array=np.random.randint(2,size=(4,4))
First question, at this time I want to make code that size can be changeable. What should I do?
top = input("Top(k):")
Second question, I want to receive k value like this and send output as much as this value.
At this time, I wanna print the top k-row indexes from the weakest to the strongest (weakest:smaller number of ones) How to do it??:(
example like this.
input
[[1,0,0,0],
[1,1,1,1],
[1,0,0,0],
[1,0,0,0]]
Top(k):2
output
0,2
if Top(k):4, output is
0,2,3,1
Numpy uses static arrays (it is implemented in C), you cannot change the size of a numpy array as you would with python lists. However, you can use the numpy.ndarray constructor to create a numpy array from python list: array = numpy.ndarray(my_python_array).
For you second answer you can use the function sum() of ndarray and use it like this:
histogram = []
for i in range(len(array_2D)):
# Store the row indexes as well as number of ones
histogram.append((i, array2D[i].sum()))
# Sort regarding the number of ones
histogram.sort(key=lambda e:e[1])
for index, val in histogram[:k]:
print(index, end=" ")
Here array2D is the numpy array you got from user input. You should parse the user input to get a numpy array before executing this code.
I started studying python and I have a question for the program. I am writing
as the first step I thought of creating a big matrix and a big vectors where I will put some smaller vectors and smaller matrices. I created at random.
I have created a function that returns the max eigen values of those small matrices and save them in a vector. Also I created a function that basically does the multiplication of the transpose of my small vectors with the small matrices that I had randomly calculated. However when I try to pass the value of the multiplication, I get the following error
"setting an array element with a sequence."
import numpy as np
from scipy import linalg as lg
import math
N=5;
n=3;
Qs=np.zeros((n,N*n))
xs=np.zeros(n*N)
qs=np.zeros(n*N)
grads=np.zeros(N*n)
Lfi=np.zeros(N)
pis=np.zeros(N*n)
pi=np.zeros(N)
phat=np.zeros(N)
j=0;
gamma=np.zeros(N)
def gradient(Q,x) :
return x.transpose().dot(Q)
def eigen(Q):
val, vec = lg.eig(Q)
return np.amax(Q)
for i in range(0,N):
A = np.random.randint(10, size=(n,n))
Qs[0:n,j:j+n] += A
x = np.random.randint(10, size=(n))
qs[j:j+n] += x
x = np.random.randint(10, size=(n))
xs[j:j+n] += x
j = j+n
Lfi[i] = eigen(A)
grads[i] = gradient(A,x)
Why do I get the error for the gradient and not for example at the Lfi?
Your gradient function returns something else than what is expected by grads. From the error message I can tell that grads is numpy array which is not as forgiving as default python list. It has a type associated with it and it requires every element to be of that type.
e.g.
a = np.array([0] * 10)
print(type(a[0]))
this will tell you that the type of elements in this array is numpy.int64 (obviously there are many types and this is just a one of them). If you try to assign some value of a different type, python will try to coerce it to numpy.int64. But obviously, there is no sensible (general) way to coerce another array or matrix to a single number.
If you try
a[0] = [1, 2, 3]
then you will receive the error mentioned by you
ValueError: setting an array element with a sequence.
And why don't you receive the error when calling eigen function? Well, because it just returns a single value, not an array. np.amax(Q) returns a single value if you don't specify axis parameter which is set to None by default.
This is basically what I am trying to do:
array = np.array() #initialize the array. This is where the error code described below is thrown
for i in xrange(?): #in the full version of this code, this loop goes through the length of a file. I won't know the length until I go through it. The point of the question is to see if you can build the array without knowing its exact size beforehand
A = random.randint(0,10)
B = random.randint(0,10)
C = random.randint(0,10)
D = random.randint(0,10)
row = [A,B,C,D]
array[i:]= row # this is supposed to add a row to the array with A,C,B,D as column values
This code doesn't work. First of all it complains: TypeError: Required argument 'object' (pos 1) not found. But I don't know the final size of the array.
Second, I know that last line is incorrect but I am not sure how to call this in python/numpy. So how can I do this?
A numpy array must be created with a fixed size. You can create a small one (e.g., one row) and then append rows one at a time, but that will be inefficient. There is no way to efficiently grow a numpy array gradually to an undetermined size. You need to decide ahead of time what size you want it to be, or accept that your code will be inefficient. Depending on the format of your data, you can possibly use something like numpy.loadtxt or various functions in pandas to read it in.
Use a list of 1D numpy arrays, or a list of lists, and then convert it to a numpy 2D array (or use more nesting and get more dimensions if you need to).
import numpy as np
a = []
for i in range(5):
a.append(np.array([1,2,3])) # or a.append([1,2,3])
a = np.asarray(a) # a list of 1D arrays (or lists) becomes a 2D array
print(a.shape)
print(a)
I would like to import just one value from a csv file. So far, I have been succesfull at using the skip_header and skip_footer options to seek out this element. It is a float value. One problem though, when I try to use this one element from my array, I get an error. Example:
import numpy as np
x = np.genfromtxt('junker.txt',skip_header=6,skip_footer=7)
print x
returns
array(10)
however
print x[0]
returns
TypeError: len() of unsized object
I just want to be able to use this value however I cannot because it's in a numpy array. Please help
a numpy array in that form is actually just a number. For example:
x = np.array([1])
Has a length of 1. However your array does not. Being just a number, you may utilize it right away! Example
x = np.array(3)
y = x + 3
print y
Will yield 3.
The length of x will yield an error because while this is an array, it is technically a zero dimensional array. Hence a length cannot be recovered from this variable.
I have a list of lists in Python that holds a mix of values, some are strings and some are tuples.
data = [[0,1,2],["a", "b", "c"]]
I am wondering if there is a way to easily convert any length list like that to a 2D Array without using Numpy. I am working with System.Array because that's the format required.
I understand that I can create a new instance of an Array and then use for loops to write all data from list to it. I was just curious if there is a nice Pythonic way of doing that.
x = len(data)
y = len(data[0])
arr = Array.CreateInstance(object, x, y)
Then I can loop through my data and set the arr values right?
arr = Array.CreateInstance(object, x, y)
for i in range(0, len(data),1):
for j in range(0,len(data[0]), 1):
arr.SetValue(data[i][j], i,j)
I want to avoid looping like that if possible. Thank you,
Ps. This is for Excel Interop where I can set a whole Range in Excel by setting it to be equal to an Array. That's why I want to convert a list to an Array. Thank you,
Thing that I am wondering about is that Array is a typed object, is it possible to set its constituents to either string or integer? I think i might be constrained to only one. Right? If so, is there any other type of data that I can use?
Is setting it to Arrayobject ensures that I can combine str/int inside of it?
Also I though I could use this:
arr= Array[Array[object]](map(object, data))
but it throws an error. Any ideas?
You can use Array.CreateInstance to create a single, or multidimensional, array. Since the Array.CreateInstance method takes in a "Type" you specify any type you want. For example:
// gives you an array of string
myArrayOfString = Array.CreateInstance(String, 3)
// gives you an array of integer
myArrayOfInteger = Array.CreateInstance(Int32, 3)
// gives you a multidimensional array of strings and integer
myArrayOfStringAndInteger = [myArrayOfString, myArrayOfInteger]
Hope this helps. Also see the msdn website for examples of how to use Array.CreateInstance.