【问题标题】:Replace data starts with '...' with np.NaN用 np.NaN 替换以 '...' 开头的数据
【发布时间】:2017-07-14 20:44:45
【问题描述】:

我有一个带有以“...”开头的字符串数据的 DataFrame。如何用 np.NaN 替换 DataFrame 中的字符串值?

我使用了以下内容:df.replace('...', np.NaN, inplace=True) .它当然不会替换所有以'...'开头的数据。

我打算使用 regExp 作为df.replace('^\.',np.NaN, inplace=True) 但它不起作用。

有人可以帮我将正则表达式传递给df.replace吗?

【问题讨论】:

    标签: python regex pandas dataframe


    【解决方案1】:

    使用df.replace,指定regex=True

    In [447]: df = pd.DataFrame({'Col1' : ['foo', '...', 'bar', '...test', '...']})
    
    In [448]: df.replace(r'^\.\.\..*', np.nan, regex=True)
    Out[448]: 
      Col1
    0  foo
    1  NaN
    2  bar
    3  NaN
    4  NaN
    

    【讨论】:

    • 对于...test,所需的输出难道不是NaN吗?
    • @ViníciusAguiar 感谢您指出这一点。我已经修好了:)
    猜你喜欢
    • 2020-04-30
    • 2022-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多