首页 > 解决方案 > 无论 Pandas python 中的类型如何,如何用文本“NULL”替换空值?

问题描述

我有一个函数可以接收数据框中的每一列(每一列都有不同的类型)。基本上我正在尝试创建一个 SQL 脚本以将值从导出的文本文件插入到数据库中,但是对于没有条目的项目,我希望添加“NULL”。对于我需要在字段开头和结尾的字符串,我的功能如下:

# Add apostrophes if needed to surround the fields, but if blank add "NULL"

    def add_apos(x):
    
    if x.isnull():
        return "NULL"
    elif x.isnumeric():
        return x
    else:
        return "\'"+x+"\'"

我已经尝试了多个版本,但我无法让它工作。我还尝试拆分函数,以便数字字段转到另一个专门用于数字字段的函数和另一个用于 str 对象的函数,但我无法让它工作。

我得到的最常见的错误是:

AttributeError: 'str' object has no attribute 'isnull'

标签: pythonpython-3.xpandasdata-cleaning

解决方案


希望这可以帮助,

def add_apos(x):
    if x is None:
        return "NULL"
    elif isinstance(x,int):
        return x
    else:
        return "\'" + x + "\'"
print(add_apos(None))
print(add_apos(987))
print(add_apos("qwer"))

在此处输入图像描述


推荐阅读