将numpy数组中的元素转换为字符串

时间:2022-06-28 21:23:41

I wrote the following script to load data from CSV file in numpy array form:

我编写了以下脚本,以numpy数组形式从CSV文件加载数据:

import numpy

sample = numpy.genfromtxt('sample_cor.csv', delimiter = ',')
print sample

and this sample looked like:

这个样本看起来是这样的:

[[  259463.392   2737830.062 ]
 [  255791.4823  2742050.772 ]
 [  249552.4949  2746152.328 ]
 [  247925.1228  2746422.143 ]
 [  262030.4697  2728966.229 ]
 [  260462.1936  2731412.856 ]
 [  260644.0281  2735003.027 ]
 [  268588.7974  2732835.097 ]]

now I want to extract every row in this array to string with a comma, for example, I expected row 1 to be converted to 259463.392,2737830.062, row 2 to be 255791.4823,2742050.772, and so on.

现在,我想要提取这个数组中的每一行以逗号作为字符串,例如,我希望第1行被转换为259463.392,2737830.062,第2行被转换为255791.4823,2742050.772,以此类推。

I tried the code below:

我试过下面的代码:

ss = numpy.array_str(sample[0])
print ss
print type(ss)

and got the result maybe not what I want,

结果可能不是我想要的,

[  259463.392  2737830.062]
<type 'str'>

(I used coords = '259467.2,2737833.87' and got the string form which was what I want: 259467.2,2737833.87)

(我用coords = '259467.2,2737833.87'得到了我想要的字符串形式:259467.2,2737833.87)

How to convert elements in a numpy array to string with a comma?

如何用逗号将numpy数组中的元素转换为字符串?

1 个解决方案

#1


4  

Here's an approach using join method -

这里有一个使用join方法的方法。

[",".join(item) for item in a.astype(str)]

Sample run -

样本运行-

In [141]: a
Out[141]: 
array([[  259463.392 ,  2737830.062 ],
       [  255791.4823,  2742050.772 ],
       [  249552.4949,  2746152.328 ],
       [  247925.1228,  2746422.143 ],
       [  262030.4697,  2728966.229 ],
       [  260462.1936,  2731412.856 ],
       [  260644.0281,  2735003.027 ],
       [  268588.7974,  2732835.097 ]])

In [142]: [",".join(item) for item in a.astype(str)]
Out[142]: 
['259463.392,2737830.062',
 '255791.4823,2742050.772',
 '249552.4949,2746152.328',
 '247925.1228,2746422.143',
 '262030.4697,2728966.229',
 '260462.1936,2731412.856',
 '260644.0281,2735003.027',
 '268588.7974,2732835.097']

#1


4  

Here's an approach using join method -

这里有一个使用join方法的方法。

[",".join(item) for item in a.astype(str)]

Sample run -

样本运行-

In [141]: a
Out[141]: 
array([[  259463.392 ,  2737830.062 ],
       [  255791.4823,  2742050.772 ],
       [  249552.4949,  2746152.328 ],
       [  247925.1228,  2746422.143 ],
       [  262030.4697,  2728966.229 ],
       [  260462.1936,  2731412.856 ],
       [  260644.0281,  2735003.027 ],
       [  268588.7974,  2732835.097 ]])

In [142]: [",".join(item) for item in a.astype(str)]
Out[142]: 
['259463.392,2737830.062',
 '255791.4823,2742050.772',
 '249552.4949,2746152.328',
 '247925.1228,2746422.143',
 '262030.4697,2728966.229',
 '260462.1936,2731412.856',
 '260644.0281,2735003.027',
 '268588.7974,2732835.097']