'convert a list to an array, out put has no comma

I tried to convert a list to an array, but the output I got has no comma.

%%writefile tem2504.txt
1 2 3 4 5 6
2 3 5 8 7 9

data = []
with open('tem2504.txt') as f:
    for line in f:
        numbers = line.split()
        print(numbers)
        print('hello')
        for number in numbers:
            data.append(float(number))
print(data)
print(type(data))
print(np.array(data))
print(type(np.array(data)))

But the out put I got has no comma between the numbers: [1. 2. 3. 4. 5. 6. 2. 3. 5. 8. 7. 9.]

['1', '2', '3', '4', '5', '6']
hello
['2', '3', '5', '8', '7', '9']
hello
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 2.0, 3.0, 5.0, 8.0, 7.0, 9.0]
<class 'list'>
[1. 2. 3. 4. 5. 6. 2. 3. 5. 8. 7. 9.]
<class 'numpy.ndarray'>

Why is that? Thank you!



Solution 1:[1]

That's just the way numpy outputs its array type as a string. It doesn't use comas, but it still functions as a list of floats. If you use the following:

import numpy as np
a = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 2.0, 3.0, 5.0, 8.0, 7.0, 9.0]
np_array = np.array(a)
for i in np_array:
     print(i)

It will list iterate through the np.array as a list:

1.0
2.0
3.0
4.0
5.0
6.0
2.0
3.0
5.0
8.0
7.0
9.0

Solution 2:[2]

This is simply how numpy displays arrays. Even in case of lists, there is no actual use of commas they are just for display.

Solution 3:[3]

You don't need to worry due to the absence of commas in the array. That's just something numpy does to display them. It doesn't affect how the arrays work.

Solution 4:[4]

In [214]: alist = [0,1,2,3]

This display/print of a list has [] and ,

In [215]: print(alist)
[0, 1, 2, 3]

The str display of an array omits the comma, as a clue that it is not a list:

In [216]: print(np.array(alist))
[0 1 2 3]

But every class also has repr format, that often is 'more informative':

In [217]: print(repr(np.array(alist)))
array([0, 1, 2, 3])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 djsumdog
Solution 2 Anshumaan Mishra
Solution 3 Zero
Solution 4 hpaulj