python - 将 Python 字典中的相同值替换为 None

标签 python function dictionary

我想用 None 值替换字典中具有“not_recorded”值的每个值。

字典:

 data = {'Date' : ['3-Mar', '20-Mar', '20-Apr', '21-Apr', '29-Apr', '7-May', '30-May', '31-May', '7-Jun', '16-Jun',
 '1-Jul', '2-Jul', '10-Jul'],
        'Site_1' : [0.5840, 0.8159, 0.7789, 0.7665, 0.8510, 0.7428, 'not_recorded', 0.6820, 0.8714, 0.8902, 'not_recorded', 0.8289, 0.6877],
        'Site_2' : [0.6196, 0.8291, 0.7686, 0.7848, 0.9935, 0.7406, 'not_recorded', 0.6952, 0.6952, 0.6952, 'not_recorded', 0.8119, 'not_recorded']}

我做错了什么?

    def replace_string_with_None(value_to_find, value_for_replacing):
        for value in data.values():
                if value == value_to_find:
                        data[value] = value_for_replacing
replace_string_with_None("not_recorded", None)
print(data)

最佳答案

这是一种方法。

例如:

data = {'Date' : ['3-Mar', '20-Mar', '20-Apr', '21-Apr', '29-Apr', '7-May', '30-May', '31-May', '7-Jun', '16-Jun',
 '1-Jul', '2-Jul', '10-Jul'],
        'Site_1' : [0.5840, 0.8159, 0.7789, 0.7665, 0.8510, 0.7428, 'not_recorded', 0.6820, 0.8714, 0.8902, 'not_recorded', 0.8289, 0.6877],
        'Site_2' : [0.6196, 0.8291, 0.7686, 0.7848, 0.9935, 0.7406, 'not_recorded', 0.6952, 0.6952, 0.6952, 'not_recorded', 0.8119, 'not_recorded']}

def replace_string_with_None(data, value_to_find, value_for_replacing):
    for key, value in data.items():
        data[key] = [value_for_replacing if i == value_to_find else i for i in value]
    return data

data = replace_string_with_None(data, "not_recorded", None)
print(data)

输出:

{'Date': ['3-Mar',
          '20-Mar',
          '20-Apr',
          '21-Apr',
          '29-Apr',
          '7-May',
          '30-May',
          '31-May',
          '7-Jun',
          '16-Jun',
          '1-Jul',
          '2-Jul',
          '10-Jul'],
 'Site_1': [0.584,
            0.8159,
            0.7789,
            0.7665,
            0.851,
            0.7428,
            None,
            0.682,
            0.8714,
            0.8902,
            None,
            0.8289,
            0.6877],
 'Site_2': [0.6196,
            0.8291,
            0.7686,
            0.7848,
            0.9935,
            0.7406,
            None,
            0.6952,
            0.6952,
            0.6952,
            None,
            0.8119,
            None]}

关于python - 将 Python 字典中的相同值替换为 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54982796/

相关文章:

python - Python 中带有条件的 lambda

python - 如何自动提取由与键关联的 numpy 数组表示的值作为字典中的单独数据

python - Boto3 cron : Parameter ScheduleExpression is not valid

python - 具有 NUMERIC(10,2) 等参数化数据类型的 Pandas to_sql

javascript - 如何像这样将函数嵌入到JavaScript中的函数中?

python - 如何在两个不同的字典中组合值,这些字典在 python 中具有相同的键

python - grep 特定时间范围内的日志文件

具有动态生成参数的 Javascript 函数

PHP MYSQL 查询未将数组传递到我的变量中

python - 从字典中绘制直方图