1

Why is the python formatting giving me this error:

>>> type(df['rMeanPSFMag'])
pandas.core.series.Series

Convert the format of the rMeanPSFMag column::

>>> df['rMeanPSFMag'] = df['rMeanPSFMag'].map('{:,.3f}'.format)
>>> type(df['rMeanPSFMag'])
pandas.core.series.Series

>>> df['rMeanPSFMag'] = df['rMeanPSFMag'].map('{:,.3f}'.format)

I then get a ValueError: Unknown format code 'f' for object of type 'str'

3
  • 1
    You want convert again float, but already converted column to string, so raise error. Need use code only once. Commented Jun 4, 2018 at 11:45
  • Okay, great. So, if I just want to keep the varilable as a float, but format it to e.g. 8 charaters, with 3 dps, how do I do that?? Commented Jun 4, 2018 at 11:52
  • Do you think df['rMeanPSFMag'] = df['rMeanPSFMag'].round(3) ? Commented Jun 4, 2018 at 11:54

1 Answer 1

2

It is expected, because column have string values, so if convert again from float it raise error:

df = pd.DataFrame({'rMeanPSFMag':[10.10235, 45.45871]})

print(df['rMeanPSFMag'].apply(type))
0    <class 'float'>
1    <class 'float'>
Name: rMeanPSFMag, dtype: object

#convert floats to strings with 3 decimals
df['rMeanPSFMag'] = df['rMeanPSFMag'].map('{:,.3f}'.format)

print(df)
  rMeanPSFMag
0      10.102
1      45.459

print(df['rMeanPSFMag'].apply(type))
0    <class 'str'>
1    <class 'str'>
Name: rMeanPSFMag, dtype: object

If want float to 3 decimals use round:

df['rMeanPSFMag'] = df['rMeanPSFMag'].round(3)
print (df)

   rMeanPSFMag
0       10.102
1       45.459

print(df['rMeanPSFMag'].apply(type))
0    <class 'float'>
1    <class 'float'>
Name: rMeanPSFMag, dtype: object

Another solution is multiple by 1000, convert to integers and divide by 1000:

df['rMeanPSFMag'] = df['rMeanPSFMag'].mul(1000).astype(int).div(1000)
print (df)

   rMeanPSFMag
0       10.102
1       45.458
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.