Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

python - numpy: is it possible to preserve the dtype of columns when using column_stack

When I use column_stack to concatenate NumPy arrays, the dtype gets converted:

a = numpy.array([1., 2., 3.], dtype=numpy.float64)
b = numpy.array([1, 2, 3], dtype=numpy.int64)
print numpy.column_stack((a, b)).dtype
>>> float64

Is there a way to preserve the dtype of the individual columns?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can stack two arrays with numpy.lib.recfunctions method and preserve the type with it:

>>> from  numpy.lib.recfunctions import append_fields

>>> a = numpy.rec.array(a, dtype=[('a', numpy.float64)])
>>> new_a = append_fields(a, 'b', b, usemask=False, dtypes=[numpy.int64])
>>> new_a
array([(1.0, 1), (2.0, 2), (3.0, 3)], 
      dtype=[('a', '<f8'), ('b', '<i8')])

>>> new_a['a']
array([ 1.,  2.,  3.])

>>> new_a['b']
array([1, 2, 3])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...