Say I've got two numpy arrays which were created this way:
zeros = np.zeros((270,270))
ones = np.ones((150,150))
How can I insert ones in zeros at position [60,60]?
I want an array that looks like a "square in the square".
I've tried the following two options:
np.put(empty, [60,60], ones)
np.put(empty, [3541], ones)
np.put[empty, [60:210,60:210], ones)
but the latter yields invalid syntax and the first two don't work either. Has anyone got an idea how this could work?
This is one way you can replace values in zeros with ones.
zeros[60:210,60:210] = ones
Related
I have a 3D array with the shape (9, 100, 7200). I want to remove the 2nd half of the 7200 values in every row so the new shape will be (9, 100, 3600).
What can I do to slice the array or delete the 2nd half of the indices? I was thinking np.delete(arr, [3601:7200], axis=2), but I get an invalid syntax error when using the colon.
Why not just slicing?
arr = arr[:,:,:3600]
The syntax error occurs because [3601:7200] is not valid python. I assume you are trying to create a new array of numbers to pass as the obj parameter for the delete function. You could do it this way using something like the range function:
np.delete(arr, range(3600,7200), axis=2)
keep in mind that this will not modify arr, but it will return a new array with the elements deleted. Also, notice I have used 3600 not 3601.
However, its often better practice to use slicing in a problem like this:
arr[:,:,:3600]
This gives your required shape. Let me break this down a little. We are slicing a numpy array with 3 dimensions. Just putting a colon in means we are taking everything in that dimension. :3600 means we are taking the first 3600 elements in that dimension. A better way to think about deleting the last have, is to think of it as keeping the first half.
Im making a 2D numpy array in python which looks like this
['0.001251993149471442' 'herfst'] ['0.002232327408019874' 'herfst'] ['0.002232327408019874' 'herfst'] ['0.002232327408019874' 'winter'] ['0.002232327408019874' 'winter']
I want to get the most common string from the entire array.
I did find some ways to do this already but all of those have the same problem that it wont work because there are 2 datatypes in the array.
Is there an easier way to get the most common element from an entire column (not row) besides just running it through a for loop and counting?
You can get a count of all the values using numpy and collections. It's not clear from your question whether the numeric values in your 2D list are actually numbers or strings, but this works for both as long as the numeric values are first and the words are second:
import numpy
from collections import Counter
input1 = [['0.001251993149471442', 'herfst'], ['0.002232327408019874', 'herfst'], ['0.002232327408019874', 'herfst'], ['0.002232327408019874', 'winter'], ['0.002232327408019874', 'winter']]
input2 = [[0.001251993149471442, 'herfst'], [0.002232327408019874, 'herfst'], [0.002232327408019874, 'herfst'], [0.002232327408019874, 'winter'], [0.002232327408019874, 'winter']]
def count(input):
oneDim = list(numpy.ndarray.flatten(numpy.array(input))) # flatten the list
del oneDim[0::2] # remove the 'numbers' (i.e. elements at even indices)
counts = Counter(oneDim) # get a count of all unique elements
maxString = counts.most_common(1)[0] # find the most common one
print(maxString)
count(input1)
count(input2)
If you want to also include the numbers in the count, simply skip the line del oneDim[0::2]
Unfortunately, mode() method exists only in Pandas, not in Numpy,
so the first step is to flatten your array (arr) and convert it to
a pandasonic Series:
s = pd.Series(arr.flatten())
Then if you want to find the most common string (and note that Numpy
arrays have all elements of the same type), the most intuitive solution
is to execute:
s.mode()[0]
(s.mode() alone returns a Series, so we just take the initial element
of it).
The result is:
'0.002232327408019874'
But if you want to leave out strings that are convertible to numbers,
you need a different approach.
Unfortunately, you can not use s.str.isnumeric() because it finds
strings composed solely of digits, but your "numeric" strings contain
also dots.
So you have to narrow down your Series (s) using str.match and
then invoke mode:
s[~s.str.match('^[+-]?(?:\d|\d+\.\d*|\d*\.\d+)$')].mode()[0]
This time the result is:
'herfst'
Consider numpy arrays arr1 and arr2. They can be any number of dimensions. For example
arr1=np.zeros([5,8])
arr2=np.ones([4,10])
I would like to put arr2 into arr1 either by cutting off excess lengths in some dimensions, or filling missing length with zeros.
I have tried:
arr1[exec(str(",:"*len([arr1.shape]))[1:])]=arr2[exec(str(",:"*len([arr2.shape]))[1:])]
which is basically the same as
arr1[:,:]=arr2[:,:]
I would like to do this preferably in one line and without "for" loops.
You could use this :
arr1[:min(arr1.shape[0], arr2.shape[0]), :min(arr1.shape[1], arr2.shape[1])]=arr2[:min(arr1.shape[0], arr2.shape[0]), :min(arr1.shape[1], arr2.shape[1])]
without any for loop.
It's the same concept you applied in second try, but with a condition to choose minimum length.
I solved this by coming up with the following. I used slice() as #hpaulj suggested. Considering I want to assign ph10 (an array) to ph14 (an array of zeros of size bound1):
ph14=np.zeros(bound1)
ph10=np.array(list1)
ind_min=np.min([ph14.shape,ph10.shape],0)
ph24=[]
for n2 in range(0,len(ind_min.shape)):
ph24=ph24+[slice(0,ind_min[n2])]
ph14[ph24]=ph10[ph24]
How can i sort an array like this: arr=[[2,1,1,2,3,3],[1,1,2,3,2,2],[1,2,1,3,2,2]]
Into: sorted_arr=[[1,1,2,3,2,2],[1,2,1,3,2,2],[2,1,1,2,3,3]]
thats not part of my code its just an example of what i need. I have an array with a lot of arrays and integers on it, and the integers are 1,2,3 i want to sort it, for example, one array is 111111111 and is in the middle of the main array, i want it at the beginning
The logic is, that in my real code i have 2 arrays and i compare them, so i have a nested loop, and to make it faster, if a very close elemnts are at the beggining it will speed a lot my code, so thats why i want to sort it, The array has a lot of arrays with splitted integers into it, so i want to sort that arrays like the integer would be 1
sorted(arr)
works for me. Have you tried it?
According to your description, I guess you want to sort the rows according to the columns by interpreting the columns as the keys of primary-order, secondary-order, etc. If that is the case, numpy.lexsort can do a good job.
Try this code
import numpy as np
arr = np.array([[2,1,1,2,3,3],
[1,1,2,3,2,2],
[1,2,1,3,2,2]])
argsorted = np.lexsort(arr.transpose()[::-1])
print(arr[argsorted])
you can easily transform arr[argsorted] to list by list(arr[argsorted])
I am just not getting this. I want to create a simple 2D array. I do not know the size, but it will be N number of rows of 3 columns. I have tried several things:
data_list[v_row][v_trade_date, v_buy_text, v_ticker]
data_list.append[v_trade_date, v_buy_text, v_ticker]
data_list[v_row].append(v_trade_date)
data_list[v_row].append(v_sell_text)
data_list[v_row].append(v_ticker)
Just not getting it. I do not need to use any FOR loop to assign the values, as each time through the outer loop, I'll be getting 3 items, and I'll assign them explicitly into different cells of that row. Maybe my thinking is wrong, and I'm thinking of 2D arrays from other languages, but any help would be great.
For appending a row:
data_list.append([v_trade_date, v_buy_text, v_ticker])
And for assigning:
data_list[v_row] = [v_trade_date, v_buy_text, v_ticker]