when trying below code get the error unsupported format string passed to Series.float How to solve this problem
Code tried:
df['a3'] = "the value is {:.2f}".format(df['a2'])
Here ,
df['a2'] consists of values [0.0,1.0,2.0] and its dtype is float64.
How do i rectify this format error, please help!
CodePudding user response:
You can't use str.format
like that. Instead, you can use apply()
to do this for every item in the a2
column:
df['a3'] = df['a2'].apply(lambda x: "the value is {:.2f}".format(x))
Output:
>>> df
a2 a3
0 0.0 the value is 0.00
1 0.1 the value is 0.10
2 0.2 the value is 0.20
Bonus: Now, a trick, which might work for you (but might not) and which might be a bit faster would be to to do something like this:
df['a4'] = 'the value is ' df['a2'].astype(str) '!!'
Output:
>>> df
a2 a3 a4
0 0.0 the value is 0.00 the value is 0.0!!
1 0.1 the value is 0.10 the value is 0.1!!
2 0.2 the value is 0.20 the value is 0.2!!