Show an array in format of scientific notation

后端 未结 2 1061
别跟我提以往
别跟我提以往 2021-02-05 18:41

I would like to show my results in scientific notation (e.g., 1.2e3). My data is in array format. Is there a function like tolist() that can convert the array to fl

相关标签:
2条回答
  • 2021-02-05 19:08

    You can format each of the elements of an array in scientific notation and then display them as you'd like. Lists cannot be converted to floats, they have floats inside them potentially.

    import numpy as np
    a = np.zeroes(shape=(5, 5), dtype=float)
    for e in a.flat:
        print "%E" % e
    

    or

    print ["%E" % e for e in a.flat]
    
    0 讨论(0)
  • 2021-02-05 19:31

    If your version of Numpy is 1.7 or greater, you should be able to use the formatter option to numpy.set_printoptions. 1.6 should definitely work -- 1.5.1 may work as well.

    import numpy as np
    a = np.zeros(shape=(5, 5), dtype=float)
    np.set_printoptions(formatter={'float': lambda x: format(x, '6.3E')})
    print a
    

    Alternatively, if you don't have formatter, you can create a new array whose values are formatted strings in the format you want. This will create an entirely new array as big as your original array, so it's not the most memory-efficient way of doing this, but it may work if you can't upgrade numpy. (I tested this and it works on numpy 1.3.0.)

    To use this strategy to get something similar to above:

    import numpy as np
    a = np.zeros(shape=(5, 5), dtype=float)
    formatting_function = np.vectorize(lambda f: format(f, '6.3E'))
    print formatting_function(a)
    

    '6.3E' is the format you want each value printed as. You can consult the this documentation for more options.

    In this case, 6 is the minimum width of the printed number and 3 is the number of digits displayed after the decimal point.

    0 讨论(0)
提交回复
热议问题