I need to append 1D arrays (coordinates) into a 2d array using numpy in python 3.6.
I can do this with lists using append, such as in the first example below.
mastlist =[]
i=0
for i in range (10):
i=i+1
coor = []
xcoor = i
ycoor =i*2
coor.append(xcoor)
coor.append(ycoor)
mastlist.append(coor)
print(mastlist)
But I want a more performant approach using numpy arrays. When I attempt to convert the list approach to an array (second example),
import numpy as np
i=0
for i in range (10):
i=i+1
centroid =np.append(i,i*2)
masterarray=np.append([centroid],axis=0)
print(masterarray)
print(masterarray)
I get the error below.
My error is:
TypeError: append() missing 1 required positional argument: 'values'
I would of expected an array such as:
[[1, 2], [2, 4], [3, 6], [4, 8], [5, 10], [6, 12], [7, 14], [8, 16], [9, 18], [10, 20]]
I have also fumbled with attempts using extend, vstack, and concatenate.
Any advice would be welcome.
I recommend you get single coordinate data firstly , then concatenate them. To my best knowledge, I dont think it can be done by np.append
The common method is np.concatenate, which I see it from cs231n class.
My sample codes are as follows:
import numpy as np
xcoor = np.arange(1,11,1).reshape(-1,1)
ycoor = np.arange(2,22,2).reshape(-1,1)
xycoor = np.concatenate((xcoor,ycoor),axis = 1)
print(xycoor)
Output:
[[ 1 2]
[ 2 4]
[ 3 6]
[ 4 8]
[ 5 10]
[ 6 12]
[ 7 14]
[ 8 16]
[ 9 18]
[10 20]]
Why not just use list comprehension?
import numpy as np
masterarray = np.array([[i,2*i] for i in range(1,11)])
output
array([[ 1, 2],
[ 2, 4],
[ 3, 6],
[ 4, 8],
[ 5, 10],
[ 6, 12],
[ 7, 14],
[ 8, 16],
[ 9, 18],
[10, 20]])
Related
For a given array of integers, perform operations on the array. Return the resulting array after all operations have been applied in the order given. Each operation contains two indices. Reverse the subarray between those zero-based indices, inclusive.
1: arr is : [1, 2, 3] 1: operations is : [[0, 2], [1, 2], [0, 2]]
2: arr is : [640, 26, 276, 224, 737, 677, 893, 87, 422, 30] 2: operations is : [[0, 9], [2, 2], [5, 5], [1, 6], [5, 6], [5, 9], [0, 8], [6, 7], [1, 9], [3, 3]]
can any one help in solving this question.
Start like this:
[1, 2, 3] -> [3, 2, 1] # first: reverse array between index 0 and 2
-> [3, 1, 2] # then: reverse array between index 1 and 2
etc.
I hope you got the idea.
def adjacent_sum(arr)
narr = []
l = arr.length
arr.each.with_index do |num,index|
if index < arr.size-1
narr << arr[index] + arr[index+1]
end
end
return narr
end
print adjacent_sum([3, 7, 2, 11]) #=> [10, 9, 13], because [ 3+7, 7+2, 2+11 ]
puts
print adjacent_sum([2, 5, 1, 9, 2, 4]) #=> [7, 6, 10, 11, 6], because [2+5, 5+1, 1+9, 9+2, 2+4]
puts
Write a method pyramid_sum that takes in an array of numbers representing the base of a pyramid. The function should return a 2D array representing a complete pyramid with the given base. To construct a level of the pyramid, we take the sum of adjacent elements of the level below.
I understand that I must make a 2-D array and use adjacent addition to build the next level of the pyramid but I don't understand the basic mechanics or thinking methodology in Ruby for two-dimensional arrays. Why am I getting array and what approach do you suggest?
base = [1, 2, 3, 4, 5]
(base.size-1).times.with_object([base]) do |_,arr|
arr << arr.last.each_cons(2).map(&:sum)
end.reverse
#=> [
# [48]
# [20, 28],
# [8, 12, 16],
# [3, 5, 7, 9],
# [1, 2, 3, 4, 5],
# ]
See Enumerable#each_cons, a lovely method.
I have a 2D array of form
[[ 1 6]
[ 2 7]
[ 5 6]
[ 6 1]
[ 6 5]
[ 7 2]]
I want the output of the form
[[ 1 6]
[ 2 7]
[ 5 6]]
How I can get this output?
Here's a solution using plain Python, but I'm sure there's a more idiomatic way with NumPy.
import numpy as np
a = np.array([
[1, 6],
[2, 7],
[5, 6],
[6, 1],
[6, 5],
[7, 2]])
seen = set()
out = []
for row in a:
elements = frozenset(row)
if elements not in seen:
seen.add(elements)
out.append(row)
print(np.array(out))
Output:
[[1 6]
[2 7]
[5 6]]
I'm looking to generate an array as follows:
array([[ 1, 2],
[ 2, 3],
[ 3, 4],
[ 4, 5],
[ 5, 6],
[ 6, 7],
[ 7, 8],
[ 8, 9],
[ 9, 10]])
Here is how I generate in NumPy:
import numpy as np
a = np.arange(1, 10)
b = np.arange(2, 11)
np.stack((a, b), axis=1)
Is there any function in NumPy that does this directly?
The shortest answer I can think of, using broadcasting black magic:
# Solution 1:
np.r_[:9][:,None]+[1,2]
# Solution 2:
np.r_['c',:9]+[1,2]
Or also using np.r_ but without broadcasting this time:
# Solution 3:
np.r_['1,2,0', :10, 1:11]
Every solution produce, as expected:
array([[ 1, 2],
[ 2, 3],
[ 3, 4],
[ 4, 5],
[ 5, 6],
[ 6, 7],
[ 7, 8],
[ 8, 9],
[ 9, 10]])
I don't know of any built-in to do this kind of arrangement, but here are some alternative solutions.
Using a half step size and np.floor:
>>> np.floor(np.arange(1.5, 10.5, .5)).reshape(9, 2)
Using np.repeat:
>>> np.repeat(np.arange(1, 11), 2)[1:-1].reshape(9, 2)
Using np.lib.stride_tricks.as_strided (imo the best method):
>>> as_strided(np.arange(1, 11), shape=(9, 2), strides=(8, 8))
Since the 2D->1D mapping you're looking to achieve is i + j = k, strides must be (1, 1) in bytes i.e. (8, 8) in bits.
I've been scanning the forums and haven't found an answer yet that I can apply to my situation. I need to be able to take an n by n array and transpose it in Python-3. The example given is that I have this list input into the function:
[[4, 2, 1], ["a", "a", "a"], [-1, -2, -3]] and it needs to be transposed to read:
[[4, 'a', -1], [2, 'a', -2], [1, 'a', -3]] So basically reading vertically instead of horizontally.
I CANNOT use things like zip or numpy, I have to make my own function.
Been rattling my brain at this for two nights and it's a huge headache. If anyone could help and then provide an explanation so I can learn it, I'd be grateful.
Edit:
I should add for reference sake that the argument variable is M. The function we're supposed to write is trans(M):
A one-liner:
def trans(M):
return [[M[j][i] for j in range(len(M))] for i in range(len(M[0]))]
result:
>>> M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> trans(M)
[[1, 4, 7], [2, 5, 8], [3, 6, 9]
# or for a non-square matrix:
>>> N = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
>>> trans(N)
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
Additional Note: If you look up the tutorial on list comprehension, one of the examples is in fact transposition of a matrix array.
A variant that should work for matrices with irregular row lengths:
m=[[3, 2, 1],
[0, 1],
[2, 1, 0]]
m_T = [ [row[c] for row in m if c < len(row)] for c in range(0, max([len(row) for row in m])) ]
Here is an in place solution that works for square matrices:
def trans(M):
n = len(M)
for i in range(n - 1):
for j in range(i + 1, n):
M[i][j], M[j][i] = M[j][i], M[i][j]
Example Usage:
def print_matrix(M):
for row in M:
for ele in row:
print(ele, end='\t')
print()
M = [[4, 2, 1], ["a", "a", "a"], [-1, -2, -3]]
print('Original Matrix:')
print_matrix(M)
trans(M)
print('Transposed Matrix:')
print_matrix(M)
Output:
Original Matrix:
4 2 1
a a a
-1 -2 -3
Transposed Matrix:
4 a -1
2 a -2
1 a -3
y=([1,2], [3,4], [5,6])
transpose=[[row[i] for row in y] for i in range(len(y[0]))]
the output is
[[1, 3, 5], [2, 4, 6]]
You can also use the function in numpy to transpose - if you need the answer as a list it is straightforward to convert back using tolist:
from numpy import transpose
M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transpose(M).tolist()
the output is
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Haven't timed it (no time!) but I strongly suspect this will be a lot faster than iterators for large arrays, especially if you don't need to convert back to a list.