4

I have a array which must keep its dtype fixed. However, after a append statement, its dtype changes. How can I append values without changing the dtype?

vertices = array([0.5, 0.0, 0.0, 1.0, 0.0, 0.0,
                  0.0, 0.5, 0.0, 0.0, 1.0, 0.0,
                  0.0, -0.5, 0.0, 0.0, 0.5, 0.0], dtype=np.float32)
print(vertices.dtype)
vertices = append(vertices, [-0.5, 0.0, 0.0, 0.0, 0.0, 1.0])
print(vertices.dtype)

Output: float32 float64

1
  • 1
    np.append is just a dumb front end to np.concatenate. You don't need it (none of us do!). Just make sure all inputs have the desired dtype. Commented Apr 3, 2020 at 19:24

2 Answers 2

5
from numpy import *
import numpy as np
vertices = array([0.5, 0.0, 0.0, 1.0, 0.0, 0.0,
                  0.0, 0.5, 0.0, 0.0, 1.0, 0.0,
                  0.0, -0.5, 0.0, 0.0, 0.5, 0.0], dtype=np.float32)
print(vertices.dtype)
vertices = append(vertices, np.array([-0.5, 0.0, 0.0, 0.0, 0.0, 1.0], dtype=np.float32))
print(vertices.dtype)

random_arr = [-0.5, 0.0, 0.0, 0.0, 0.0, 1.0]
print(np.array(random_arr).dtype)

float32
float32
float64

By default, numpy assigns float64 datatype on your float array (check the last random_arr), so once you concatenate one float32 and one float64 array, obviously final array will be casted to float64. So, just specify the dtype when creating numpy arrays to be safe.

Sign up to request clarification or add additional context in comments.

Comments

1

You can append the new data as a numpy array, passing in the type when you convert it as well.

import numpy as np

vertices = np.array([0.5, 0.0, 0.0, 1.0, 0.0, 0.0,
                  0.0, 0.5, 0.0, 0.0, 1.0, 0.0,
                  0.0, -0.5, 0.0, 0.0, 0.5, 0.0], dtype=np.float32)
print(vertices.dtype)
vertices = np.append(vertices, np.array([-0.5, 0.0, 0.0, 0.0, 0.0, 1.0], dtype=np.float32))
print(vertices.dtype)

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.