在Python中用nan替换浮点列中的点 [英] Replace dots in a float column with nan in Python
本文介绍了在Python中用nan替换浮点列中的点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的数据帧df
I have a data frame df like this
df = pd.DataFrame([
{'Name': 'Chris', 'Item Purchased': 'Sponge', 'Cost': 22.50},
{'Name': 'Kevyn', 'Item Purchased': 'Kitty Litter', 'Cost': '.........'},
{'Name': 'Filip', 'Item Purchased': 'Spoon', 'Cost': '...'}],
index=['Store 1', 'Store 1', 'Store 2'])
我想将费用"列中的缺失值替换为 np.nan
.到目前为止,我已经尝试过:
I want to replace the missing values in 'Cost' columns to np.nan
. So far I have tried:
df['Cost']=df['Cost'].str.replace("\.\.+", np.nan)
和
df['Cost']=re.sub('\.\.+',np.nan,df['Cost'])
,但它们似乎都无法正常工作.请帮忙.
but neither of them seem to work properly. Please help.
推荐答案
通过 regex = True
开关使用 DataFrame.replace
.
df = df.replace('\.+', np.nan, regex=True)
df
Cost Item Purchased Name
Store 1 22.5 Sponge Chris
Store 1 NaN Kitty Litter Kevyn
Store 2 NaN Spoon Filip
模式 \.+
指定一个或多个点.您也可以使用 [.] +
作为具有相同效果的模式.
The pattern \.+
specifies one or more dots. You could also use [.]+
as a pattern to the same effect.
这篇关于在Python中用nan替换浮点列中的点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文