python - 如何从字符串中删除小数点后的零删除点后的所有零
问题描述
我有一个带有对象列的数据框,可以说 col1,它的值如下:1.00、1、0.50、1.54
我希望输出如下所示:1、1、0.5、1.54 基本上,如果零后没有任何数字,则删除十进制值后的零。请注意,我需要数据框的答案。pd.set_option 和 round 对我不起作用。
解决方案
如果想要将整数和浮点数转换为没有尾随的字符串,请0
使用or :map
apply
df = pd.DataFrame({'col1':[1.00, 1, 0.5, 1.50]})
df['new'] = df['col1'].map('{0:g}'.format)
#alternative solution
#df['new'] = df['col1'].apply('{0:g}'.format)
print (df)
col1 new
0 1.0 1
1 1.0 1
2 0.5 0.5
3 1.5 1.5
print (df['new'].apply(type))
0 <class 'str'>
1 <class 'str'>
2 <class 'str'>
3 <class 'str'>
Name: new, dtype: object
推荐阅读
- sql - ORACLE SQL - 如何找到上一个辞职日期和加入日期之间的间隔?
- python - 在 Pandas 中调用 read_csv 后无法重用输入流
- firebase-authentication - 自定义参数 HL 代表什么?
- ios - RxSwift 打断日语 - 罗马字输入
- javascript - 如何在电子中将目标 URL 与我自己的资源挂钩?
- python - 如何根据分辨率将已经拆分的日期分成两列?
- php - 如何使用 laravel 更改前端的显示布局
- arm - 在运行时检测 arm 处理器上的扩展超截面支持
- python - 如何旋转 matplotlib 图形?
- javascript - 有没有办法从“mysql”数据库中获取数据并在我的 javascript 文件中使用它?