用不同类型的值过滤字典
我正在尝试根据字典中的值进行筛选(这个字典里有不同的数据类型),但是遇到了一个错误:
ValueError: 一个包含多个元素的数组的真假值是不明确的。请使用 a.any() 或 a.all()
我想要获取字典中所有与 'YALE' 这个值对应的记录。
这是我的代码:
dataset = {
'timeseires': array([[
[ -5.653222, 7.39066 , 20.651941, 4.07861 ,-11.752331, -34.611312],
[ -5.653222, 7.39066 , 20.651941, 4.07861 ,-11.752331, -34.611312]
]]),
'site': array(['YALE', 'KKI'], dtype='<U8')
}
dataset = data.tolist()
def filter(pairs):
key, value = pairs
filter_key = 'site'
if key == filter_key and value == 'YALE':
return True
else:
return False
final_dic = dict(filter(filter, dataset.items()))
print(final_dic)
我期望的输出是:
> dataset = {
> 'timeseires': array([[
> [ -5.653222, 7.39066 , 20.651941, 4.07861 ,-11.752331, -34.611312]
> ]]),
> 'site': array(['KKI'], dtype='<U8')
> }
2 个回答
0
根据你想要的输出结果,你可以使用 dict
推导式来实现类似的功能:
import numpy as np
filtered_indices = np.where(dataset["site"] == "YALE")[0].tolist()
dataset = {k: np.delete(v, filtered_indices) for k, v in dataset.items()}
{'timeseires': array([ 7.39066 , 20.651941, 4.07861 , -11.752331, -34.611312,
-5.653222, 7.39066 , 20.651941, 4.07861 , -11.752331,
-34.611312]), 'site': array(['KKI'], dtype='<U8')}
0
根据你提供的输出信息,看来你的任务是提取与'YALE'
这个索引对应的'timeseries'
值。
下面这段代码应该可以解决你的问题:
def filter_dictionary_by_value(dataset, value):
index_value = np.where(dataset['site'] == value)[0]
filtered_timeseries = dataset['timeseries'][index_value]
filtered_dict = {
'timeseries': filtered_timeseries,
'site': np.array([value], dtype='<U8')
}
如果这不是你想要的结果,请在问题中说明得更具体一些。