【问题标题】:How to substitute NaN for a text in a DataFrame?如何用 NaN 替换 DataFrame 中的文本?
【发布时间】:2021-11-20 21:52:30
【问题描述】:

我有一个DataFrame,我需要将特定列的单元格内容更改为文本内容(例如“未注册”)。

我正在尝试不同的选择,以下是其中的一些:

dftotal.fillna({"Computer_OS":"not registered", "Computer_OS_version":"not registered"}, inplace=True)

dftotal.loc[(dftotal["Computer_OS"]=="NaN"),"Computer_OS"] = "not registered"

【问题讨论】:

  • 您在使用 pandas 作为数据框吗?如果是这样,最好在您的问题中包含该信息并添加熊猫标签。
  • 这能回答你的问题吗? Replacing column values in a pandas DataFrame
  • 请澄清您的具体问题或提供更多详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: python dataframe nan


【解决方案1】:

假设 Computer_OS 列中的所有值都是字符串数据类型,否则您需要先更改数据类型。

import numpy as np
import pandas as pd
import re

def txt2nan(x):
    """
    if given string x contains alphabet 
    return NaN else original x.

    Parameters
    ----------
    x : str
    """
    if re.match('[a-zA-Z]', x):
        return np.nan
    else:
        return x

df = pd.DataFrame({"os":["tsd", "ssad d", "sd", "1","2","3"]})

df["os"] = df["os"].apply(txt2nan)

更好的解决方案是将上述操作向量化:

df["os"] = np.where(df["os"].str.match('[a-zA-Z]'), np.nan, df["os"])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 2023-01-24
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    • 2022-11-29
    • 2021-02-25
    相关资源
    最近更新 更多