2

I have a multi-dimensional numpy array with float elements. I want to convert the elements to strings, but NOT have the elements change to scientific notation.

An example:

import numpy as np
np.set_printoptions(suppress=True)

x = np.array([0.000095]) # prints as "[0.000095]"
x = x.astype(str) # this is now "['9.5e-05']", whereas I want "['0.000095']"

2 Answers 2

1

you can use np.nditer to achieve this for multidimensional arrays

let

my_multidimensional_array = np.ones((3,3,3)) * 0.000095

my_multidimensional_array
Out[105]: 
array([[[0.000095, 0.000095, 0.000095],
        [0.000095, 0.000095, 0.000095],
        [0.000095, 0.000095, 0.000095]],

       [[0.000095, 0.000095, 0.000095],
        [0.000095, 0.000095, 0.000095],
        [0.000095, 0.000095, 0.000095]],

       [[0.000095, 0.000095, 0.000095],
        [0.000095, 0.000095, 0.000095],
        [0.000095, 0.000095, 0.000095]]])

def np_to_string(my_multidimensional_array):
    result = my_multidimensional_array.copy().astype(str)
    with np.nditer(result, op_flags=['readwrite']) as it:
        for x in it:
            x[...] = np.format_float_positional(float(x))

    return result

And it works!

print(np_to_string(my_multidimensional_array))
[[['0.000095' '0.000095' '0.000095']
  ['0.000095' '0.000095' '0.000095']
  ['0.000095' '0.000095' '0.000095']]

 [['0.000095' '0.000095' '0.000095']
  ['0.000095' '0.000095' '0.000095']
  ['0.000095' '0.000095' '0.000095']]

 [['0.000095' '0.000095' '0.000095']
  ['0.000095' '0.000095' '0.000095']
  ['0.000095' '0.000095' '0.000095']]]
Sign up to request clarification or add additional context in comments.

Comments

0

use np.format_float_positional function to convert to string

import numpy as np
np.set_printoptions(suppress=True)
y = []
x = np.array([0.000095,0.2131]) # prints as "[0.000095]"
for item in x:
    y.append(np.format_float_positional(item))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.