0

If I have an array like this:

 array([['10      2       1967    19.7    7.5'],
        ['10      3       1967    18.3    21.0'],
        ['10      4       1967    17.6    0.0']])

How do I remove the quotations and add a comma in between each value? Such that I get something like this:

 array([[10, 2, 1967, 19.7, 7.5],
        [10, 3, 1967, 18.3, 21.0],
        [10, 4, 1967, 17.6, 0.0]])
3
  • Do you want to convert the single numbers to something? int or float? With a numpy array you can't mix both. Commented Jan 28, 2019 at 16:45
  • 1
    What the source of this array? It would be better to correct it before it's created, rather fix it after. The source and targets are very different arrays. One is 1d with string elements. The other is 2d with numeric elements. The quotes and commas tell us about the arrays, but they aren't what define them. Commented Jan 28, 2019 at 16:56
  • I missed something before. Your source array is 2d, with shape (3,1). I neglected that inner set of []. The key descriptors of a numpy array are shape and dtype. Commented Jan 28, 2019 at 18:23

3 Answers 3

2

Regular NumPy arrays must have a single dtype. In this case, float may be appropriate:

A = np.array([['10      2       1967    19.7    7.5'],
              ['10      3       1967    18.3    21.0'],
              ['10      4       1967    17.6    0.0']])

B = np.array([x[0].split() for x in A], dtype=float)

# array([[   10. ,     2. ,  1967. ,    19.7,     7.5],
#        [   10. ,     3. ,  1967. ,    18.3,    21. ],
#        [   10. ,     4. ,  1967. ,    17.6,     0. ]])
Sign up to request clarification or add additional context in comments.

Comments

0

This is one approach.

from numpy import array
import ast
l = array([['10      2       1967    19.7    7.5'],
        ['10      3       1967    18.3    21.0'],
        ['10      4       1967    17.6    0.0']])

l = [list(map(ast.literal_eval,  j.split()))  for i in l for j in i]
print(l)

Output:

[[10, 2, 1967, 19.7, 7.5], [10, 3, 1967, 18.3, 21.0], [10, 4, 1967, 17.6, 0.0]]

Note: You cannot have both int and float in np.array.

Comments

0

Other couple of options:

array = np.array([['10      2       1967    19.7    7.5'],
                  ['10      3       1967    18.3    21.0'],
                  ['10      4       1967    17.6    0.0']])

new_ary1 = np.array([ [ float(n) for n in e[0].split() ] for e in array ])
new_ary2 = np.array([ np.array(e[0].split(), dtype=float) for e in array ])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.