0
import numpy as np

I have this numpy array:

data = np.array(data)
# assume it has x number of rows and y columns

1) At one point I replace the 10th column values as follows with string value:

data[data[0::,10] == "C",10] = "0"

2) In a for loop with index i, I do this comparison by converting the string to float-

x = (data[0::,10].astype(np.float) == i)

This throws a ValueError: could not convert string to float:

Why?

2
  • Can you verify all other string values in 10th column are present (non-empty strings) and are numeric? Commented Jun 19, 2013 at 13:56
  • I have edited the original post to say the I am concerned with the 10th column. Commented Jun 22, 2013 at 11:58

1 Answer 1

1

From your error message there is some '' (empty string) in the column you are trying to convert. Be sure that the column you are comparing has only strings that ar convertible to float. You can create a isfloat() function to do that for you:

def isfloat(x):
    try:
        float(x)
        return True
    except:
        return False
isfloat = np.vectorize(isfloat)

Then use in your example:

data[ data[:,col] == 'C', col ] = '0'

x = (data[ isfloat(data[:,col]), col ].astype(np.float) == i)
Sign up to request clarification or add additional context in comments.

3 Comments

@Selvam when you create a function in Python you can pass some arguments. x is an argument of the function isfloat()
Thanks. And what is happening in this line isfloat = np.vectorize(isfloat) ?
the isfloat() function words only for single values, when you do isfloat = np.vectorize(isfloat) you redefine the function using numpy.vectorize which is equivalent than implementing a Python for loop over the an array of floats, making the new isfloat() applicable to an array...

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.