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

时间:2016-10-26 12:05:43

标签: arrays string numpy

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

import numpy

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

示例看起来像:

[[  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行转换为259463.392,2737830.062,第2行转换为255791.4823,2742050.772,依此类推。

我尝试了以下代码:

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

并且结果可能不是我想要的,

[  259463.392  2737830.062]
<type 'str'>

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

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

1 个答案:

答案 0 :(得分:6)

这是一种使用join method -

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

示例运行 -

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']