16
votes

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

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.

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)

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

1
The form without the , is just the normal way that numpy arrays are displayed. It helps distinguish them from Python lists. The , is not an integral part of either a list or an array. It's just a display feature. - hpaulj

1 Answers

17
votes

Here's an approach using join method -

[",".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']