简体   繁体   中英

ValueError: Unknown format code 'f' for object of type 'str'

Can someone please help me resolve the error code I get in the title.

I've tried adding float as mentioned in stuff I've read online, but this doesn't work either.

`df['Conv. Rates']=df['Conv. Rates'].apply(lambda x: " 
{0:.2f}%".format(x))
df.head()`

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/folders/_c/86br91rx4fx2j35rrmbfkp6h0000gn/T/ipykernel_6452/1132564018.py in <module>
----> 1 df['Conv. Rates']=df['Conv. Rates'].apply(lambda x: "{0:.2f}%".format(x))
      2 df.head()

/opt/anaconda3/lib/python3.9/site-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwargs)
   4431         dtype: float64
   4432         """
-> 4433         return SeriesApply(self, func, convert_dtype, args, kwargs).apply()
   4434 
   4435     def _reduce(

/opt/anaconda3/lib/python3.9/site-packages/pandas/core/apply.py in apply(self)
   1086             return self.apply_str()
   1087 
-> 1088         return self.apply_standard()
   1089 
   1090     def agg(self):

/opt/anaconda3/lib/python3.9/site-packages/pandas/core/apply.py in apply_standard(self)
   1141                 # List[Union[Callable[..., Any], str]]]]]"; expected
   1142                 # "Callable[[Any], Any]"
-> 1143                 mapped = lib.map_infer(
   1144                     values,
   1145                     f,  # type: ignore[arg-type]

/opt/anaconda3/lib/python3.9/site-packages/pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()

/var/folders/_c/86br91rx4fx2j35rrmbfkp6h0000gn/T/ipykernel_6452/1132564018.py in <lambda>(x)
----> 1 df['Conv. Rates']=df['Conv. Rates'].apply(lambda x: "{0:.2f}%".format(x))
      2 df.head()

ValueError: Unknown format code 'f' for object of type 'str'

The problem is that x is a string and not a float as you expect, so "12.345" is just six characters, the same as if it were "python" , and Python doesn't know how to format it with decimal points.

You can do

df['Conv. Rates'].astype("float")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM