当前位置:优学网  >  在线题库

从字典内的字符串数组中删除nan

发表时间:2022-07-24 01:27:31 阅读:165

我在从字典中的数组中删除nan时遇到问题.以下是我正在处理的数据:

{'test1': array(['a','b','c','d','e','f',nan,'g '], dtype=object)}

我试过这个代码:

test_dict = {key: values for key, values in sdg_keywords_dict.items() if not isnan(values)}

不幸的是,它返回只有大小为1的数组才能转换为Python标量.

🎖️ 优质答案
  • Here is a simple way to do what you're asking:

    test_dict = {key: np.array([v for v in values if v is not np.nan]) for key, values in sdg_keywords_dict.items()}

    Output:

    {'test1': array(['a', 'b', 'c', 'd', 'e', 'f', 'g '], dtype=object)}

    Note that if your values were numeric, you could use np.isnan() for vectorized boolean indexing like this:

    sdg_keywords_dict = {'test1': np.array([1,2,3,4,5,6,np.nan,7])}
    test_dict = {key: values[~np.isnan(values)] for key, values in sdg_keywords_dict.items()}

    Input: {'test1': array([ 1., 2., 3., 4., 5., 6., nan, 7.])}

    Output: {'test1': array([1., 2., 3., 4., 5., 6., 7.])}

    However, the presence of elements of type str in your array means that np.isnan() will raise an exception:

    TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
  • 相关问题