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]
1
  • Maybe this post is what you are actually looking to perform. Commented Jun 8, 2016 at 19:24

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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')
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.
2

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

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.