python - pandas 检查 DataFrame 中的单个值是否为数字
问题描述
我有一个看起来像这样的数据框:
a b c d
-1000 2000.1 NaN text1
NaN -500 450 text2
1240.6 NaN -100 text3
有些值包含小数,有些包含负号,有些是整数。
我想将所有包含整数的列的格式统一为带有 0 的浮点数。即-1000
应该是-1000.000
等等。
我采用的方法相当简单,但它并没有奏效。我试过这个:
df = df.apply(lambda x: x.astype(str) + '.000' if x.str.isnumeric().all() else x)
但是,此函数无法按预期工作,因为它会检查整个 pd.Series 是否为数字,但并非总是如此。
如何改进此功能以查看每个单独的值并.000
根据需要添加?
解决方案
IIUC 类似于您当前的方法,您可以尝试使用pd.to_numeric
+的自定义函数applymap
,请注意格式化浮点数会改变 dtypes
def myf(x):
s = pd.to_numeric(x,errors='coerce')
return np.where(pd.notna(s),'{0:.3f}'.format(s),x)
df.applymap(myf)
a b c d
0 -1000.000 2000.100 nan text1
1 nan -500.000 450.000 text2
2 1240.600 nan -100.000 text3
推荐阅读
- node.js - 从设备的位置获取 lat 和 lng
- c# - 发送 SOAP 样式请求时出现 RestSharp 问题
- python - 尝试不同版本的网站地址 - Python
- node.js - 尝试安装 asyncawait 模块,总是失败并返回相同的错误
- c - 如何使用 getcontext() 和 setcontext() 进行多线程处理?
- r - 替换 tibble 中的日期 NA
- java - Java不好的做法:将return语句添加到仅用于测试的方法?
- angular - 工具提示作为动态组件
- javascript - 在使用角度文件删除时选择所有复选框时出现问题
- javascript - 以数组和多维对象的角度显示 API 结果