用 Python 中的 nan 替换浮点列中的点

Replace dots in a float column with nan in Python

我有一个像这样的数据框 df

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'])

我想将 'Cost' 列中的缺失值替换为 np.nan。到目前为止我已经尝试过:

df['Cost']=df['Cost'].str.replace("\.\.+", np.nan)

df['Cost']=re.sub('\.\.+',np.nan,df['Cost'])

但它们似乎都无法正常工作。请帮忙。

使用 DataFrame.replaceregex=True 开关。

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

模式\.+指定一个或多个点。您也可以使用 [.]+ 作为模式来达到同样的效果。