3

When trying to convert a Pandas Series to float, I get this error message. It refers to an empty string (" "), which is not a np.nan. Just an empty string.

I tried replacing " " by np.nan, but it doesn't do anything. I also tried replacing " " by "" but it also doesn't do anything.

import pandas as pd
import numpy as np

df = pd.DataFrame(np.array([[1, 2, 3], [4, " ", 6], [7, 8, 9]]), 
                  columns=['a', 'b', 'c'])

df.astype(float)

ValueError: could not convert string to float:

I want to replace these " " by NaN values, in a large dataframe.

2
  • What float value are you expecting for " " ? Commented May 16, 2019 at 14:53
  • 1
    df.apply(pd.to_numeric, args=('coerce',)) Commented May 16, 2019 at 14:59

1 Answer 1

3

You can use df.replace() function to perform this operation

df.replace(r'^\s*$', np.nan, regex=True)
Sign up to request clarification or add additional context in comments.

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.