格式化系列float数据类型的float



在尝试以下代码时,获取传递给Series的错误不支持的格式字符串浮动如何解决这个问题

尝试的代码:

df['a3'] = "the value is {:.2f}".format(df['a2'])

在这里,df['a2'] consists of values [0.0,1.0,2.0] and its dtype is float64.

如何更正此格式错误,请帮助!

不能那样使用str.format。相反,您可以使用apply()a2列中的每个项目执行此操作:

df['a3'] = df['a2'].apply(lambda x: "the value is {:.2f}".format(x))

输出:

>>> 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

额外奖励:现在,一个可能对你有效(但可能无效(并且可能更快的技巧是做这样的事情:

df['a4'] = 'the value is ' + df['a2'].astype(str) + '!!'

输出:

>>> 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!!

最新更新