ValueError:序列的真值不明确(API NaN处理)

2024-04-19 05:02:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在django rest框架中开发一个API,根据您的输入参数,您可以得到不同的响应。 API正在计算将根据数据库返回给用户的指标。你知道吗

我编写了一个函数来处理NaN值,如下所示:

def nan_to_none(value):
    if not isinstance(value, str) and value is not None and np.isnan(value):
        return None
    return value

这是响应中弹出错误的元素:

 "prog": nan_to_none(row["average_items_prog"])

这是引发问题的SQL行:

  ((((coalesce(qte_art, 0) / nullif(nb_client, 0)) - (coalesce(qte_art_n1, 0) / nullif(nb_client_n1, 0))) / (coalesce(qte_art_n1, 0) / nullif(nb_client_n1, 0))) * 100) as average_items_prog,

下面是错误信息:

  File "C:\Users\wdc\views.py", line 464, in get
    "prog": nan_to_none(row["average_items_prog"])},
  File "C:\Users\wdc\views.py", line 28, in nan_to_none
    if not isinstance(value, str) and value is not None and np.isnan(value):
  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py", line 1478, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我不知道该怎么修!你知道吗


Tags: andtononeisvaluenotitemsnan
1条回答
网友
1楼 · 发布于 2024-04-19 05:02:41

尝试更改:

"prog": nan_to_none(row["average_items_prog"])

使用^{}

"prog": row["average_items_prog"].apply(nan_to_none)

测试:

s = pd.Series(['a', 0, 0, 1, None, np.nan])
print (s)
0       a
1       0
2       0
3       1
4    None
5     NaN
dtype: object

def nan_to_none(value):
    if not isinstance(value, str) and value is not None and np.isnan(value):
        return None
    return value

print (s.apply(nan_to_none))
#in your solution
#"prog": row["average_items_prog"].apply(nan_to_none)
0       a
1       0
2       0
3       1
4    None
5    None
dtype: object

似乎解决方案也应该通过测试来简化np.nan != np.nan

def nan_to_none(value):
    if value != value:
        return None
    return value

print (s.apply(nan_to_none))
#in your solution
#"prog": row["average_items_prog"].apply(nan_to_none)
0       a
1       0
2       0
3       1
4    None
5    None
dtype: object

或用^{}设置None

print (s.mask(s.isna(), None))
#in your solution
#"prog": row["average_items_prog"].mask(s.isna(), None)
0       a
1       0
2       0
3       1
4    None
5    None
dtype: object

相关问题 更多 >