## Change location of string in numpy array

numpy replace string

numpy array to list

numpy replace values condition

numpy where

numpy array of string type

numpy char array to string

numpy replace array with another array

I have a numpy array that contains strings.

index1 = ['level4','level3','level2','UNKNOWN','level1']

I want to arrange this numpy array such that `'UNKNOWN'`

is always the first string in the array.

Desired array:

index1 = ['UNKNOWN','level4','level3','level2','level1']

Sorting of level is not desirable

##### Simplest answer

If you literally just want `'UNKNOWN'`

to be in front, then the easiest and most computationally efficient way to do so is to just swap it with the `0`

th element:

index1 = np.array(['level4','level3','level2','UNKNOWN','level1']) # find the index of 'UNKNOWN' ix = np.flatnonzero(index1 == 'UNKNOWN')[0] # swap values index1[[0, ix]] = index1[[ix, 0]] print(index1) # output: # ['UNKNOWN' 'level3' 'level2' 'level4' 'level1']

##### Preserve the original order of the `level`

elements

If you want the `level`

elements to have the same order in the output as in the input, here's a (slightly more complicated but still pretty simple) way to make that happen:

index1 = np.array(['level4','level3','level2','UNKNOWN','level1']) # find the index of 'UNKNOWN' ix = np.flatnonzero(index1 == 'UNKNOWN')[0] # shift values u = index1[ix] index1[1:ix + 1] = index1[:ix] index1[0] = u print(index1) # output: # ['UNKNOWN' 'level4' 'level3' 'level2' 'level1']

##### Don't use `partition`

If you don't want the results to be sorted, then you shouldn't use `numpy.partition`

:

index1 = np.array(['level4','level3','level2','UNKNOWN','level1']) index1.partition(np.flatnonzero(index1 == 'UNKNOWN')) print(index1) # output: # ['UNKNOWN' 'level1' 'level2' 'level3' 'level4']

**Shortest way to replace parts of strings in NumPy array,** Use python list comprehension: L = ['HD\,315', 'HD\,318' ] print [s.replace('HD\,' , 'HD ') for s in L]. But it uses for. Alternatively you can use map So, it depends on what you want to achieve, why do you want to store a string in an array filled for the rest with numbers? If that really is what you want, you can set the datatype of the NumPy array to string:

You can use `np.roll`

:

import numpy as np index1 = np.array(['level4','level3','level2','UNKNOWN','level1']) position = np.where(index1 == 'UNKNOWN')[0][0] index1[:position + 1] = np.roll(index1[:position + 1], 1) print(index1)

array(['UNKNOWN', 'level4', 'level3', 'level2', 'level1'], dtype='<U7')

**String operations,** This module provides a set of vectorized string operations for arrays of type For each element, return the lowest index in the string where substring sub is Using numpy.where(), elements of the NumPy array ndarray that satisfy the conditions can be replaced or performed specified processing.numpy.where — NumPy v1.14 Manual Here, the following contents will be described.Overview of np.where() Multiple conditions Replace the elements that satisfy the con

partition() will permit to reorder your array, but will be sorted.

index1.partition(np.where(index1=='UNKNOWN')[0][0])

**Modify Numpy array to store an arbitrary length string,** The dtype of any numpy array containing string values is the maximum length of any string present in the array. Once set, it will only be able to store new string having length not more than the maximum Change the dtype of the country. NumPy does not change the data type of the element in-place (where the element is in array) so it needs some other space to perform this action, that extra space is called buffer, and in order to enable it in nditer () we pass flags= ['buffered']. Example. Iterate through the array as a string: import numpy as np.

**numpy.chararray,** Starting from numpy 1.4, if one needs arrays of strings, it is recommended to Memory address of the start of the array data. replace (self, old, new[, count]). If you try to assign a long string to a normal numpy array, it truncates the string: >>> a = numpy.array(['apples', 'foobar', 'cowboy']) >>> a[2] = 'bananas' >>> a array(['apples', 'foobar', 'banana'], dtype='|S6') But when you use dtype=object, you get an array of python object references. So you can have all the behaviors of python strings:

**NumPy Array Slicing,** Slicing arrays. Slicing in python means taking elements from one given index to another given index. We pass slice instead of index like this: [start:end] . We can ndarray2str -- Converts numpy ndarray to bytes string. str2ndarray -- Converts binary str back to numpy ndarray. def ndarray2str(a): # Convert the numpy array to string a = a.tostring() return a On the receiver side, the data is received as a 'xmlrpc.client.Binary' object. You need to access the data using '.data'.

**numpy.chararray,** Change shape and size of array in-place. rfind(sub[, start, end]), For each element in self, return the highest index in the string where substring sub This explains why it doesn't work but it doesn't explain what to do instead. In my case I have a column of strings (object type from numpy's point of view) and a function to map those strings to integers that I would like to use to transform the string column into an integer column. – Joseph Garvin Aug 10 '19 at 21:52

##### Comments

- You also sort the levels. Is this desired?
- No, sorting of level is not desirable.
- Do you want to sort lists or numpy arrays? The code you show in the question creates a list.
- Does stackoverflow.com/a/37487543/3005167 or stackoverflow.com/a/45799487/3005167 answer your question?
- This does not preserve the order of the other elements
- @anishtain4 What exactly do you mean? The original order of the
`level`

elements was`(4, 3, 2, 1)`

, which is the same order that the`level`

elements have in Tomothy's output. - Please explain your answer.
- Took me a second, but then I realized that the use of
`partition`

doesn't answer the question. The result will be sorted.