Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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

def charArrayToAsciiMatrix(strNumpyArray):
 for i in range(strNumpyArray):
    if(i==0):
        AsciiMatrix=numpy.matrix(ord[[c for c in strNumpyArray[i]]])
    else:
        AsciiMatrix=numpy.vstack(AsciiMatrix,ord[[c for c in strNumpyArray[i]]])

is there a efficient way of doing this?

share|improve this question
    
Assumption is that all the strings are padded to same length. – gman Apr 18 '14 at 16:24
2  
please provide sample data – emeth Apr 18 '14 at 16:29
    
Sample data will be input:["aa","aa"] output:[92,92;92,92] – gman Apr 18 '14 at 19:14
up vote 0 down vote accepted

How is this?

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)
share|improve this answer
    
Thank you @slushy this is better than my solution – gman Apr 18 '14 at 19:18

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.