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?
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
The elements of a NumPy array, or simply an array, are usually numbers, but can also be boolians, strings, or other objects.
Iterate over each integer element using a for loop such as for element in list . Convert the int to a string using str(element) and append it to the new string list using the list. append() method.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With