Read printed numpy array

后端 未结 2 1793
借酒劲吻你
借酒劲吻你 2020-12-17 23:11

Sometimes the printed numpy array is provide to share the data such as this post. So far, I converted that manually. But the array in the post is too big to con

相关标签:
2条回答
  • 2020-12-17 23:31

    You can use re to treat the string and then create the array using eval():

     import re
     from ast import literal_eval
    
     import numpy as np
    
     a = """[[[ 0 1]
              [ 2 3]]]"""
     a = re.sub(r"([^[])\s+([^]])", r"\1, \2", a)
     a = np.array(literal_eval(a))
    
    0 讨论(0)
  • 2020-12-17 23:43

    The other reply works great, but some shortcuts can be taken if the values are numeric. Furthermore, you may have an array with many dimension and even many orders. Given npstr, your str(np.array):

    import re, json
    import numpy as np
    
    # 1. replace those spaces and newlines with commas.
    # the regex could be '\s+', but numpy does not add spaces.
    t1 = re.sub('\s',',',npstr)
    # 2. covert to list
    t2 = json.loads(t1)
    # 3. convert to array
    a = np.array(t2)
    

    In a single line (bad form sure, but good for copypasting):

    a = np.array(json.loads(re.sub('\s',',',npstr)))
    
    0 讨论(0)
提交回复
热议问题