I have an array of size 300x5. In this the column with index 3 consists if some index and column with index 4 consists of corresponding values.
I have created new array in which I am trying to assign the values in index 4 at index 3 locations in this new array. I tried this but it throws an error.
new_arr[old_arr[:,3]] = old_arr[:,4]
One of the example related to what I want to do
new_arr = np.ones((200,1))
new_arr[[2,3,4]] = [22,44,11]
It throws an error
ValueError: shape mismatch: value array of shape (3,) could not be broadcast to indexing result of shape (3,1)
With this code : new_arr[old_arr[:,3]] you try to access new_arr that index come from values are in old_arr[:,3] and you got IndexError.
Is this help you?
new_arr = np.zeros((300, 5))
new_arr[:,3] = old_arr[:,4]
For edited question you need reshape:
new_arr = np.ones((200,1))
new_arr[[2,3,4]] = np.array([2,4,6]).reshape(3,1)
# OR
# new_arr[2:5] = np.array([22,44,11]).reshape(3,1)
Related
I tried to find cosine_similarity that compare pivot table and object using .loc, and the result says
ValueError: Expected 2D array, got 1D array instead: array=[4. 4. 3. ... 3. 3. 3.]. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
So, i tried to followed the suggestion, but it doesn't work, it says "Cannot compare multidimensional index" , could you guys help me and explain to me what should i do?
this my code:
#delete related_test
for i in range(len(collab_rated_test_fix)):
ratings_test_df = ratings_test_df.drop(ratings_test_df.loc[(ratings_test_df.user_id == user_id_test) &\
(ratings_test_df.book_id == collab_rated_test_fix[i])]\
.index)
#pivot table
user_book_rating = pd.pivot_table(ratings_test_df, values="rating", index="book_id",columns="user_id")
user_book_rating = user_book_rating.fillna(user_book_rating.mean())
user_id_test = 9923
#cosine similarity
rel_user = pd.DataFrame(columns=['userId_1', 'userId_2','similarity'])
for rows, mean in user_book_rating.iteritems():
sim = cosine_similarity(user_book_rating.loc[ : , user_id_test], user_book_rating.loc[ : , rows]) #error
rel_user = rel_user.append({'UserId_1': user_id_test, 'UserId_2': rows, 'similarity': sim}, ignore_index=True)
rel_user['userId_1'] = rel_user['userId_1'].apply(int)
rel_user['userId_2'] = rel_user['userId_2'].apply(int)
I am new to Swift and am struggling to work out how to determine the size of a multidimensional array.
I can use the count function for single arrays, however when i create a matrix/multidimensional array, the output for the count call just gives a single value.
var a = [[1,2,3],[3,4,5]]
var c: Int
c = a.count
print(c)
2
The above matrix 'a' clearly has 2 rows and 3 columns, is there any way to output this correct size.
In Matlab this is a simple task with the following line of code,
a = [1,2,3;3,4,5]
size(a)
ans =
2 3
Is there a simple equivalent in Swift
I have looked high and low for a solution and cant seem to find exactly what i am after.
Thanks
- HB
Because 2D arrays in swift can have subarrays with different lengths. There is no "matrix" type.
let arr = [
[1,2,3,4,5],
[1,2,3],
[2,3,4,5],
]
So the concept of "rows" and "columns" does not exist. There's only count.
If you want to count all the elements in the subarrays, (in the above case, 12), you can flat map it and then count:
arr.flatMap { $0 }.count
If you are sure that your array is a matrix, you can do this:
let rows = arr.count
let columns = arr[0].count // 0 is an arbitrary value
You must ask the size of a specific row of your array to get column sizes :
print("\(a.count) \(a[0].count)")
If you are trying to find the length of 2D array which in this case the number of rows (or # of subarrays Ex.[1,2,3]) you may use this trick: # of total elements that can be found using:
a.flatMap { $0 }.count //a is the array name
over # of elements in one row using:
a[0].count //so elemints has to be equal in each subarray
so your code to get the length of 2D array with equal number of element in each subarray and store it in constant arrayLength is:
let arrayLength = (((a.flatMap { $0 }.count ) / (a[0].count))) //a is the array name
I have a numpy array A of size 10 with values ranging from 0-4. I want to create a new 2-D array B from this with its ith column being a vector corresponding to the ith element of A.
For example, the value 1 as the first element of A would correspond to B having a column vector [0,1,0,0,0] as it's first column. A having 4 as its third element would correspond to B having it's 3rd column as [0,0,0,1,0]
I have the following code:
import numpy as np
A = np.random.randint(0,5,10)
B = np.ones((5,10))
iden = np.identity(5, dtype=np.float64)
for i in range(0,10):
a = A[i]
B[:,i:i+1] = iden[:,a:a+1]
print A
print B
The code is doing what it's supposed to be doing but I am sure there are more efficient ways of doing this. Can anyone please suggest some?
That could be solved by initializing an array of zeros and then integer-indexing into it with indices from A and assigning 1s, like so -
M,N = 5,10
A = np.random.randint(0,M,N)
B = np.zeros((M,N))
B[A,np.arange(len(A))] = 1
I have a 100 X 1 (n1) cell array with each cell holding indices of a bigger data set(100 X 100, n2). I made a nested loop in order to access each individual element(index) and compare the values of another data set with these indices with a if condition. If the condition succeeds, I want to delete that element from the original cell array into a new cell array. However when I set the element to [] in matlab, the value of the cell array does not change. The code is below:
for i = 1:length(n1)
for j = 1:length(n1{i, 1})
if n2(i,n1{i,1}(1,j)) > n3(i) && n2(i, n1{i,1}(1,j)) > n4(n1{i, 1}(1, j))
n1{i,1}(1,j) == [];
end
end
end
I take that n1(i,1) is always a row vector so you should use,
n1{i,1}(j) = [];
If n1(i,1) is not a column or row then removing an element from middle would be impossible.
for example:
A = {[1 2 3],[5 8 9]}
A{1,2}(1,2) = []
gives the error: A null assignment can have only one non-colon index.
But A{1,2}(2) = [] is okey.
my program in R creates an n-dimensional array.
PVALUES = array(0, dim=dimensions)
where dimensions = c(x,y,z, ... )
The dimensions will depend on a particular input. So, I want to create a general-purpose code that will:
Store a particular element in the array
Read a particular element from the array
From reading this site I learned how to do #2 - read an element from the array
ll=list(x,y,z, ...)
element_xyz = do.call(`[`, c(list(PVALUES), ll))
Please help me solving #1, that is storing an element to the n-dimensional array.
Let me rephrase my question
Suppose I have a 4-dimensional array. I can store a value and read a value from this array:
PVALUES[1,1,1,1] = 43 #set a value
data = PVALUES[1,1,1,1] #use a value
How can I perform the same operations using a function of a vector of indexes:
indexes = c(1,1,1,1)
set(PVALUES, indexes) = 43
data = get(PVALUES, indexes) ?
Thank you
Thanks for helpful response.
I will use the following solution:
PVALUES = array(0, dim=dimensions) #Create an n-dimensional array
dimensions = c(x,y,z,...,n)
Set a value to PVALUES[x,y,z,...,n]:
y=c(x,y,z,...,n)
PVALUES[t(y)]=26
Reading a value from PVALUES[x,y,z,...,n]:
y=c(x,y,z,...,n)
data=PVALUES[t(y)]
The indexing of arrays can be done with matrices having the same number of columns as there are dimensions:
# Assignment with "[<-"
newvals <- matrix( c( x,y,z,vals), ncol=4)
PVALUES[ newvals[ ,-4] ] <- vals
# Reading values with "["
PVALUES[ newvals[ ,-4] ]