0

I am trying to append a value q at certain position of the 2d array using numpy but I get an error at line of code is: a[r,c]='Q' as

ValueError: could not convert string to float: Q

#!/bin/python

import sys
import numpy as np
#n=int(raw_input())


n,k = raw_input().strip().split(' ')

n,k = [int(n),int(k)]

a=np.zeros((n,n))
r,c = raw_input().strip().split(' ')

r,c = [int(r)-1,int(c)-1]

a[r,c]='Q'  # ValueError: could not convert string to float: Q

print a 
3
  • 'Q' is a string. Your array is numerical, so it can't take a string. Can you clarify what you're trying to do?
    – perigon
    Jul 17, 2017 at 6:43
  • So i have an input with coordinate numbers.Here r and c is the coordinate position where i need to place a character Q.You could skip the for loop section...those have some different functionality.The only thing I wanted to do is to set a character in the numpy array given its coordinates. Jul 17, 2017 at 6:59
  • You could try an object array: docs.scipy.org/doc/numpy/reference/arrays.html But if you need to store numbers and strings in the same structure, that's a strong indication that a Numpy array isn't the right tool for the job (or that you don't actually need to store them in the same structure).
    – perigon
    Jul 17, 2017 at 7:02

1 Answer 1

0

If you want to place characters into an array you need an array that takes data of character or string type. The default data type in numpy arrays is floating point, which is not compatible with strings. Hence the error message.

Setting data type to <U1 (unicode) or <S1 (byte string) will tell numpy that the array takes strings of length one (i.e. a character) or an empty string:

a = np.zeros((3, 4), dtype='<U1')
a[1, 2] = 'Q'
print(a)
# [['' '' '' '']
#  ['' '' 'Q' '']
#  ['' '' '' '']]

Note that if you try to insert a longer string (a[0, 0] = 'ABC') it will only take the first character. If you insert a number the number will be converted to string and only the first character inserted (a[0, 0] = 42 -> '4').

3
  • This is the output:[[u'' u'' u'' u'' u''] [u'' u'' u'1' u'' u''] [u'' u'' u'' u'' u''] [u'' u'1' u'Q' u'' u''] [u'' u'' u'' u'' u'1']] Jul 17, 2017 at 7:13
  • how do i remove the u's Jul 17, 2017 at 7:14
  • Ah, you're on Python 2 :) Then use dtype='<S1'. The u's just indicate that these are unicode strings.
    – MB-F
    Jul 17, 2017 at 7:15

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.