3

I have a dataframe, DF of columns of data as such:

        X       Y         Z     DIST_1
0       309000  563250    0     681483125
1       309000  563300    0     679910525
2       309000  563350    0     678342925

Upon attempting to run math.sqrt on DIST_1 with the following

DF['DIST'] = math.sqrt(DF['DIST_1'])

I am getting

TypeError: cannot convert the series to <class 'float'>

I have tried running three separate functions, on the individual column and the entire DataFrame, to fix this problem:

DF['DIST_1'] = pd.to_numeric(DF['DIST_1'])

DF['DIST_1'] = (DF['DIST_1']).astype(float)

DF= DF.applymap(float)

Each of these appears to have the desired results of changing DIST_1 to a float. Here is the output after running

DF['DIST_1'] = (DF['DIST_1']).astype(float)

        X       Y         Z     DIST_1
0       309000  563250    0     681483125.0
1       309000  563300    0     679910525.0
2       309000  563350    0     678342925.0

Again I run

DF['DIST'] = math.sqrt(DF['DIST_1'])

but the result is again

TypeError: cannot convert the series to <class 'float'>

What is the error in my code or my approach?

3
  • Did you try the map function? I think sqrt only works on a number, not a pandas series, so maybe you could do it with the map function. Commented Feb 19, 2018 at 12:46
  • Yes. This changes all columns to floats but I'm still getting the same error. Commented Feb 19, 2018 at 12:47
  • DF['DIST_1'] is this one a list ? Commented Feb 19, 2018 at 12:56

2 Answers 2

4

The problem is that math.sqrt can only take a single number, not a pandas.Series. One way is to use apply, as @Kalyan recommended in the other answer.

The easier solution is to use a function that can handle a vector of floats, numpy.sqrt:

import numpy as np
DF['DIST'] = np.sqrt(DF['DIST_1'])

This should also be significantly faster than repeatedly applying the math.sqrt function to every element of the series.

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

Comments

1

you can try the following

DF['DIST_1'] = DF['DIST_1'].apply(math.sqrt)

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.