首页 > 解决方案 > 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根据需要添加?

标签: pythonpandasdataframeseries

解决方案


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

推荐阅读