使用None替换Python字典中的相同值

问题描述 投票:0回答:2

我想替换字典中的每个值,其中“not_recorded”值为None值。

快译通:

 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)
python function dictionary
2个回答
2
投票

这是一种方法。

例如:

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]}

0
投票

data.values()

是一个列表列表。您需要添加另一个循环才能迭代内部列表并与'not_recorded'进行比较

© www.soinside.com 2019 - 2024. All rights reserved.