熊猫检查DataFrame中的各个值是否为数字

问题描述 投票:0回答:2

我有一个看起来像这样的数据框:

   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

python pandas dataframe series
2个回答
0
投票

[IIUC与您当前的方法类似,您可以尝试使用pd.to_numeric + pd.to_numeric的自定义函数,请注意,格式化浮点数会更改dtypes]

applymap

applymap

0
投票

定义以下功能:

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
© www.soinside.com 2019 - 2024. All rights reserved.