logo
down
shadow

What does the String mean in numpy.r_?


What does the String mean in numpy.r_?

By : Ferryn Xenakis
Date : November 22 2020, 03:01 PM
I hope this helps you . I haven't used the string parameter of r_ much; it's easier, for me, to work directly with concatanate and its variantes.
But looking at the docs:
code :
'0.2.0'
 axis = 0
 make it 2d
 start with 0d

In [79]: np.r_['0,2,0', [1,2,3], [4,5,6]]
Out[79]: 
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]])
In [80]: np.concatenate(([1,2,3], [4,5,6]))
Out[80]: array([1, 2, 3, 4, 5, 6])
In [81]: np.concatenate(([1,2,3], [4,5,6]))[:,None]
Out[81]: 
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]])
In [83]: alist = ([1,2,3], [4,5,6]) 
In [86]: [np.expand_dims(a,1) for a in alist]
Out[86]: 
[array([[1],
        [2],
        [3]]), array([[4],
        [5],
        [6]])]
In [87]: np.concatenate(_, axis=0)
Out[87]: 
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]])
np.r_['0,2,0',[1,2,3], [[4],[5],[6]]]
np.r_['0,2,0',[1,2,3], np.expand_dims([4,5,6],1)]
np.r_['0,2,0',[1,2,3], np.atleast_2d([4,5,6]).T]
In [105]: np.atleast_2d([4,5,6])
Out[105]: array([[4, 5, 6]])

In [103]: np.r_['0,2,1',[1,2,3],[4,5,6]]
Out[103]: 
array([[1, 2, 3],
       [4, 5, 6]])
In [107]: np.r_['1,2,1',[1,2,3], [4,5,6]]
Out[107]: array([[1, 2, 3, 4, 5, 6]])
In [108]: np.r_['1,2,0',[1,2,3], [4,5,6]]
Out[108]: 
array([[1, 4],
       [2, 5],
       [3, 6]])
array(newobj, copy=False, subok=True, ndmin=ndmin)
In [111]: np.array([1,2,3], ndmin=2)
Out[111]: array([[1, 2, 3]])
In [112]: np.array([1,2,3], ndmin=2).transpose(1,0)
Out[112]: 
array([[1],
       [2],
       [3]])


Share : facebook icon twitter icon
Python numpy: Convert string in to numpy array

Python numpy: Convert string in to numpy array


By : Idris Fakiri
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I am writing this answer so if for any future references: I am not sure what is the correct solution in this case but I think What @David Robinson initially publish was the correct answer due to one reason: Cosine Similarity values can not be greater than one and when I use NP.array(v1fColor.split(","), dtype=NP.uint8) option I get strage values which are above 1.0 for cosine similarity between two vectors.
So I wrote a simple sample code to try out:
code :
import numpy as np
import numpy.linalg as LA

def testFunction():
    value1 = '2,3,0,80,125,15,5,0,0,0,0,0,0,0,0,0,0,0,0,0,2,4,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0'
    value2 = '2,137,0,4,96,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0'
    cx = lambda a, b : round(np.inner(a, b)/(LA.norm(a)*LA.norm(b)), 3)
    #v1fColor = np.array(map(int,value1.split(',')))
    #v2fColor =  np.array(map(int,value2.split(',')))
    v1fColor = np.array( value1.split(','), dtype=np.uint8 )
    v2fColor = np.array( value2.split(','), dtype=np.uint8 )
    print v1fColor
    print v2fColor
    cosineValue = cx(v1fColor, v2fColor)
    print cosineValue

if __name__ == '__main__':
    testFunction()
v1fColor = np.array(map(int,value1.split(',')))
v2fColor =  np.array(map(int,value2.split(','))) 
convert string numpy array to a ascii numpy matrix

convert string numpy array to a ascii numpy matrix


By : dannyboy
Date : March 29 2020, 07:55 AM
like below fixes the issue I have been looking for an efficient way for converting a string numpy array to a two dimensional ASCII matrix in python. So for this is the best that I could come up with , How is this?
code :
import numpy as np

def add_word_as_ordinal(arr, word):
    arr.extend([ord(ch) for ch in word])
    return arr

def char_array_to_ascii_matrix(char_array):
    result = np.matrix(reduce(add_word_as_ordinal, char_array, []))
    result.shape = len(char_array), len(char_array[0])
    return result

my_array = np.array("JustA Flesh Wound".split())
my_matrix = char_array_to_ascii_matrix(my_array)
Convert numpy array to a string using numpy.array_str()

Convert numpy array to a string using numpy.array_str()


By : Andrew Culver
Date : March 29 2020, 07:55 AM
will help you I have a 2 dimensional numpy array. I am trying to make pairs of each row with every other row. , Maybe then a posible answer is:
code :
import numpy as np
def pair(matrix,i,j):
    str1=''
    for value in matrix[i]:
        str1+=str(value)+' '
    # Delete one extra space
    str1=str1[:-1]

    str2=''
    for value in matrix[j]:
        str2+=str(value)+' '
    str2=str2[:-1]
    return str1+', '+str2

matrix=np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]])

print pair(matrix,0,1)
print pair(matrix,0,2)
converting numpy of string to numpy characters python

converting numpy of string to numpy characters python


By : zhougj
Date : March 29 2020, 07:55 AM
With these it helps I am reading data from a URL and trying to convert it to digits for further analysis on jupyter. It is a gene sequence where each gene would code for 4 binary digits. A --> 0001, C --> 0010, G --> 0100 and T --> 1000. For example, I want to go from CGGT to 0010010001001000. So far, I've been able to remove the empty space and convert it to a string. However I am unable to go from string to char and char to digits. I am using numpy arrays and have made these attempts but to no avail. , Here is a method using a lookup table:
code :
>>> alphabet = np.array(list('ACGT'))
>>> alphabet
array(['A', 'C', 'G', 'T'], dtype='<U1')
>>> alph_as_num = alphabet.view(np.int32)
>>> alph_as_num
array([65, 67, 71, 84], dtype=int32)
>>> lookup_1 = np.zeros((alph_as_num.max()+1), dtype='S4')
>>> lookup_1[alph_as_num] = [b'0001000'[i:i+4] for i in range(4)]
>>> lookup_2 = np.zeros((alph_as_num.max()+1), dtype=np.uint8)
>>> lookup_2[alph_as_num] = 1 << np.arange(4)
>>> lookup_3 = np.zeros((alph_as_num.max()+1, 4), dtype=np.uint8)
>>> lookup_3[alph_as_num[::-1]] = np.identity(4)
>>> seq
array(['CATTTCTCCACCATTTTGGTTTTTCATTGATCCGTTAGGTGGAGCCGGACTATGTCTACCGAAAGATGCACCTGCGCCGGGTCTGGTCTATCTCTTAATG'],
      dtype='<U100')
>>> lookup_1[seq.view(np.int32)]
array([b'0010', b'0001', b'1000', b'1000', b'1000', b'0010', b'1000',
       b'0010', b'0010', b'0001', b'0010', b'0010', b'0001', b'1000',
       b'1000', b'1000', b'1000', b'0100', b'0100', b'1000', b'1000',
       b'1000', b'1000', b'1000', b'0010', b'0001', b'1000', b'1000',
       b'0100', b'0001', b'1000', b'0010', b'0010', b'0100', b'1000',
       b'1000', b'0001', b'0100', b'0100', b'1000', b'0100', b'0100',
       b'0001', b'0100', b'0010', b'0010', b'0100', b'0100', b'0001',
       b'0010', b'1000', b'0001', b'1000', b'0100', b'1000', b'0010',
       b'1000', b'0001', b'0010', b'0010', b'0100', b'0001', b'0001',
       b'0001', b'0100', b'0001', b'1000', b'0100', b'0010', b'0001',
       b'0010', b'0010', b'1000', b'0100', b'0010', b'0100', b'0010',
       b'0010', b'0100', b'0100', b'0100', b'1000', b'0010', b'1000',
       b'0100', b'0100', b'1000', b'0010', b'1000', b'0001', b'1000',
       b'0010', b'1000', b'0010', b'1000', b'1000', b'0001', b'0001',
       b'1000', b'0100'], dtype='|S4')
>>> lookup_1[seq.view(np.int32)].view('S400')
array([b'0010000110001000100000101000001000100001001000100001100010001000100001000100100010001000100010000010000110001000010000011000001000100100100010000001010001001000010001000001010000100010010001000001001010000001100001001000001010000001001000100100000100010001010000011000010000100001001000101000010000100100001000100100010001001000001010000100010010000010100000011000001010000010100010000001000110000100'],
      dtype='|S400')
>>> lookup_2[seq.view(np.int32)]
array([2, 1, 8, 8, 8, 2, 8, 2, 2, 1, 2, 2, 1, 8, 8, 8, 8, 4, 4, 8, 8, 8,
       8, 8, 2, 1, 8, 8, 4, 1, 8, 2, 2, 4, 8, 8, 1, 4, 4, 8, 4, 4, 1, 4,
       2, 2, 4, 4, 1, 2, 8, 1, 8, 4, 8, 2, 8, 1, 2, 2, 4, 1, 1, 1, 4, 1,
       8, 4, 2, 1, 2, 2, 8, 4, 2, 4, 2, 2, 4, 4, 4, 8, 2, 8, 4, 4, 8, 2,
       8, 1, 8, 2, 8, 2, 8, 8, 1, 1, 8, 4], dtype=uint8)
>>> seq
array([['CCCT'],
       ['GCGA']], dtype='<U4')
>>> lookup_3[seq.view(np.int32)].reshape(len(seq), -1)
array([[0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0],
       [0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1]], dtype=uint8)
How to use the NumPy string formatter to print a NumPy array where the output string is dependent on the array value?

How to use the NumPy string formatter to print a NumPy array where the output string is dependent on the array value?


By : user2259809
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further The keyword argument formatter for array2string needs the type of the elements of the array which you want to replace, not the type which you're converting to.
So, in your example, instead of str you should use float, since 0., 1. and 2. are floats.
code :
import numpy as np

arr = np.zeros((2, 2))
arr[(0, 0)] = 1
arr[(0, 1)] = 2
printValues = {0: 'a', 1: 'b', 2: 'c'}
print(np.array2string(arr, formatter={'all': lambda x: printValues[int(x)]}))
Related Posts Related Posts :
  • django how to use Max and Count on the same field in back-to-back annotations
  • Using the OR operator seems to only take the first of two conditions when used with np.where filter
  • Elegant Dataframe Operations in Pandas
  • Change metadata of pdf file with pypdf2
  • How can I animate a set of points with matplotlib?
  • error: (-215) count >= 0 && (depth == CV_32F || depth == CV_32S) in function arcLength
  • OpenStack KeyStone SSL Exception When Creating an Instance of KeyStone
  • pyspark: The system cannot find the path specified
  • How can I set path to load data from CSV file into PostgreSQL database in Docker container?
  • Summation in python dictionary
  • DRF 3.7.0 removed handling None in fields and broke my foreign key source fields. Is there a way around it?
  • Error with Padlen in signal.filtfilt in Python
  • Abstract matrix multiplication with variables
  • Reading binary data on bit level
  • How to replace multiple instances of a sub strings in a string using a for loop (in a function)?
  • py2neo cypher create several relations to central node in for loop
  • [python-3]TypeError: must be str, not int
  • How to exit/terminate a job earlier and handle the raised exception in apscheduler?
  • python, print intermediate values while loop
  • python to loop over yaml config
  • D3.js is not recognized by PyCharm
  • Access the regularization paths obtained from ElasticNetCV in sklearn
  • Pattern table to Pandas DataFrame
  • Get the earliest date from a column (Python Pandas) after csv.reader
  • Get SystemError: Parent module '' not loaded, cannot perform relative import when trying to import numpy in a Cython Ext
  • Bash or Python : Append and prepend a string recursively in all .tex files
  • Changing a certain index of boolean list of lists change others, too
  • complex dataframe filtering request on the last occurence of a value in Panda/Python [EDIT]
  • How to repeatedly get the contents of a Text widget every loop with tkinter?
  • How to call the tornado.queues message externally
  • How can I use regex in python so that characters not included are disallowed?
  • Discarding randmly scattered empty spaces in pandas data frame
  • Get sums grouped by date by same column filtered by 2 conditions
  • Element disappears when I add an {% include %} tag inside my for loop
  • Django Rest Framework with either a slug or a pk lookup field for the DetailAPIView
  • Flask doesn't stream on Lambda
  • Generate all permutations of fixed length where the elements come from two different sets
  • Making function for calculating distance
  • How to handle multiprocessing based on the limit of CPU's
  • Django - static files is not working
  • Remove x axis and y axis black lines with matplotlib
  • tkinter: assigning multiple functions to one button
  • flask-jwt-extended: Fake Authorization Header during testing (pytest)
  • Setting pandas dataframe value based on row and column conditions
  • swig char ** as a pointer to a char *
  • Confusion over `a` and `b` attributes from scipy.stats.uniform
  • How can I do groupy.apply() without sort my index?
  • Querying Google Cloud datastore with ancestor not returning anything
  • Read value from one thread in Python: queue or global variable?
  • Django - context process query being repeated 102 times
  • Convert a list of images and labels to np array to train tensorflow
  • Lambda not supporting NLTK file size
  • Numpy ndarray image pixel mean for pixel values greater than zero: Normalizing image
  • Understanding output of np.corrcoef for two matrices of different sizes
  • Finding longest perfect match between two strings
  • what is wrong with my cosine similarity? Tensorflow
  • How to manage user content in django?
  • Receiving unsupported operand error while comparing random number and user input.
  • How to wrap the process of creating start_urls in scrapy?
  • How to mark 'duplicated sequence' in pandas?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org