gpt4 book ai didi

python - 比较字符串出现错误 ValueError : The truth value of a Series is ambiguous. 使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

转载 作者:太空宇宙 更新时间:2023-11-03 14:58:22 25 4
gpt4 key购买 nike

我尝试使用 if 条件使用以下代码更新列中的某些值:

if df['COLOR_DESC'] == 'DARK BLUE':
df['NEW_COLOR_DESC'] = 'BLUE'

但我收到以下错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

那么这段代码有什么问题呢?

最佳答案

为了回答您的直接问题,问题在于表达式 df['COLOR_DESC'] == 'DARK BLUE'结果是一系列 bool 值。错误消息告诉您没有一种明确的方法可以将该数组转换为单个 bool 值,如 if要求。

解决办法其实就是不使用if ,因为您没有应用 ifDARK_BLUE 的每个元素。直接使用 bool 值作为掩码:

rows = (df['COLOR_DESC'] == 'DARK BLUE')
df.loc[rows, 'COLOR_DESC'] = 'BLUE'

您必须使用loc更新原文df因为如果你将其索引为 df[rows]['COLOR_DESC'] ,您将获得所需子集的副本。在副本中设置值不会传播回原始版本,您甚至会收到有关此情况的警告。

例如:

>>> df = pd.DataFrame(data={'COLOR_DESC': ['LIGHT_RED', 'DARK_BLUE', 'MEDUIM_GREEN', 'DARK_BLUE']})
>>> df
COLOR_DESC
0 LIGHT_RED
1 DARK_BLUE
2 MEDUIM_GREEN
3 DARK_BLUE

>>> rows = (df['COLOR_DESC'] == 'DARK BLUE')
>>> rows
0 False
1 True
2 False
3 True
Name: COLOR_DESC, dtype: bool

>>> df.loc[rows, 'COLOR_DESC'] = 'BLUE'
>>> df
COLOR_DESC
0 LIGHT_RED
1 BLUE
2 MEDUIM_GREEN
3 BLUE

关于python - 比较字符串出现错误 ValueError : The truth value of a Series is ambiguous. 使用 a.empty、a.bool()、a.item()、a.any() 或 a.all(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45335993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com