0

I have the following df where some values in the df are strings (those with %) while other ones aren't.

                          test    overall
Quents Ratio            270.01%  256.02%
Amount sulphur            0.17     0.19
Amount salt                  -    20.89
amount silica             4.29%    6.84%

I would like to make all the values numeric given that I would like to carry out some analysis among the 2 columns.

Desired output:

                          test    overall
Quents Ratio            270.01   256.02
Amount sulphur            0.17     0.19
Amount salt                  -    20.89
amount silica             4.29     6.84

What I have tried is to:

def numeric_df(df):
    df_detail=df.loc[['Quents Ratio','amount silica'],:]
    df_detail= df_detail.apply(lambda x:str(x)[:-1])
    return df

But returns same initial df.

How could I obtain the desired output?

4
  • do you need replace - to NaN? Commented Aug 13, 2017 at 9:12
  • No I prefer to mantain it Commented Aug 13, 2017 at 9:13
  • hmmm, but then values cannot be numeric, because - is string. Commented Aug 13, 2017 at 9:14
  • Didn't thought about that, was going apply a 'to_numeric' without thinking that '-' could give me further problems Commented Aug 13, 2017 at 9:14

1 Answer 1

1

I think you need replace, but values contains also -, so impossible convert to numeric:

 df = df.replace('%', '', regex=True)

If need all values numeric and values contains only - chars:

df = df.replace({'%': '', '^-$':np.nan}, regex=True).astype(float)
print (df)
                  test  overall
Quents Ratio    270.01   256.02
Amount sulphur    0.17     0.19
Amount salt        NaN    20.89
amount silica     4.29     6.84

Another solution with to_numeric - it replace all non numeric to NaNs too:

df = df.replace('%', '', regex=True).apply(pd.to_numeric, errors='coerce')
print (df)
                  test  overall
Quents Ratio    270.01   256.02
Amount sulphur    0.17     0.19
Amount salt        NaN    20.89
amount silica     4.29     6.84
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.