我想用“无”值替换字典中具有“ 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)
答案 0 :(得分:1)
这是一种方法。
例如:
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]}
答案 1 :(得分:0)
data.values()
是列表的列表。您需要添加另一个循环以迭代内部列表并与“ not_recorded”进行比较