1

I want to put a string to an array location but I get an error:

ValueError: could not convert string to float

My code is the following:

k = np.ceil(99/8)

rs = np.zeros((int(k), 10))

for i in range(0, int(k)):
    rs[i, 0] = "FREQ"
    for j in range(1,9):
        rs[i, j] = rs_imp[8*k+j, 0]
Ajay
  • 18,086
  • 12
  • 59
  • 105
Kostas Belivanis
  • 397
  • 1
  • 5
  • 17
  • Maybe [this post](http://stackoverflow.com/questions/6999617/how-to-assign-a-string-value-to-an-array-in-numpy) is what you are actually looking to perform. – Nickil Maveli Jun 08 '16 at 19:24

2 Answers2

2

You have an array of floats. You want to put a string value to an element of that array. It is not possible.

quantummind
  • 2,086
  • 1
  • 14
  • 20
2

Your array is implicitly a float array, but you can change the data type to object to be able to include both floats and strings:

rs = np.zeros((int(k), 10), dtype='object')

But this is going to rob you of potential optimizations and may cause unexpected problems later on.

Sounds like an XY problem. Why do you think you need to add the string "FREQ" into this array? What are you really trying to do?

Riaz
  • 874
  • 6
  • 15
  • It is a XY problem that I want to separate and create files with specific format so that I can use the XY as an input. Thank you very very much. It worked this way. – Kostas Belivanis Jun 08 '16 at 19:48
  • How can I write that array now to a .txt file though? When I tried to do np.savetxt('test.txt', rsf, delimiter=',') I got Mismatch between array dtype ('object') and format specifier ('%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e,%.18e') – Kostas Belivanis Jun 08 '16 at 21:12
  • Because the array is no longer of type `float`, the default formatting codes (like `%e`) are not valid. You could do this: `np.savetxt('test.txt', rsf, delimiter=',', fmt='%s')` and it should do what you need, but if the point of the question was to add "FREQ" as a prefix to each line of a file containing numbers, there are cleaner ways to achieve this than to create a mixed-type array. By the way, an XY problem is defined [here](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Riaz Jun 09 '16 at 00:16