[英]Concatenate strings from a 2D numpy array
I want to concatenate a string from a 2d numpy
array like this, 我想连接像这样的2d
numpy
数组中的字符串,
for x in np.ndindex(mat.shape[0]):
concat = ""
for y in range(len(columns)):
concat += str(mat[x][2 + y])
where mat
is a 2d array containing string
s or int
s in each cell, columns
is a list of column names for mat
, eg ['A', 'B', 'C', 'D']
, using mat[x][2 + y]
to avoid concatenating strings from the 1st two columns. mat
是一个包含每个单元格中的string
s或int
的二维数组, columns
是mat
的列名列表,例如['A', 'B', 'C', 'D']
,使用mat[x][2 + y]
避免连接前两列的字符串。 I am wondering what is the best way to do it, probably in a more concise/efficient way. 我想知道最好的方法是什么,可能是以更简洁/有效的方式。
You have been a little vague in your definition of concatenate — I hope that the following is enough to get you started 你在连接的定义中有点模糊 - 我希望以下内容足以让你开始
print('\n'.join(' '.join(str(x) for x in row[2:]) for row in mat))
The external join
joins the rows with a newline, the internal one joins a few of the elements of each row in mat
— if you are not after ALL the elements except the first two, modify to please you the upper limit of the slice... 外部
join
加入行以一个换行符,内部一个加入了几个在各行的元素的mat
-如果你除了前两个的所有元素之后都没有了,修改就拜托你了切片的上限.. 。
Note that str(x)
leaves string elements undisturbed and formats numeric items in a reasonable way. 请注意,
str(x)
使字符串元素不受干扰,并以合理的方式格式化数字项。
Ab -using the fact that we are dealing with a 2D
array, we can resort to just one loop - AB -使用我们正在处理一个事实
2D
数组,我们可以诉诸只是一个循环-
["".join(i) for i in mat[:,2:].astype(str)]
Sample run - 样品运行 -
In [143]: mat
Out[143]:
array([[1, 1, 0, 3, 1, 1],
[3, 0, 1, 1, 1, 0],
[2, 2, 1, 2, 1, 1]])
In [144]: ["".join(i) for i in mat[:,2:].astype(str)]
Out[144]: ['0311', '1110', '1211']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.