简体   繁体   English

如何将二维 numpy 数组中的所有数字转换为字符串?

[英]How to convert all numbers in a 2d numpy array to strings?

I have a 2d numpy array of ints called M. I would like to convert all the ints to strings returning a 2d numpy array of the same shape.我有一个名为 M 的 2d numpy 整数数组。我想将所有整数转换为返回相同形状的 2d numpy 数组的字符串。 How can you do that?你怎么能那样做?

I tried map(str, M) but that doesn't work as it converts the individual rows into strings.我尝试了map(str, M)但这不起作用,因为它将各个行转换为字符串。

You can use astype to cast the array to particular type您可以使用astype将数组转换为特定类型

m = np.array([[1,2,3], [4,5,6]])

m = m.astype(str)
m
array([['1', '2', '3'],
       ['4', '5', '6']], dtype='<U21')

If I have understood it right, you are trying to convert all integer elements in the array to a string.如果我理解正确,您正在尝试将数组中的所有 integer 元素转换为字符串。 To do so, this should work:为此,这应该有效:

np.char.mod('%d',M)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM