Search code examples
pythonprintingnumpy-ndarrayscientific-notation

Python: How to print an ndarray in scientific notation (rounded) as part of a print statement


I have an ndarray that I want to print in scientific notation with rounding as part of a sentence, this is what I currently have

data_arr = np.array([12345, 12345])
print('This is the data ', *data_arr)

and the output is

This is the data  12345 12345

Is there a way to print in scientific notation, with rounding, preferably in one line, like below?

This is the data  1.2e+04 1.2e+04

Solution

  • String formating seems to be the way to go. Example:

    data_arr = np.array([12345, 12345])
    print('This is the data {:.1e} {:.1e}'.format(*data_arr))
    

    prints what you're looking for. To adjust the number of figures after the dot to, for example, three, just change 1e to 3e.