gpt4 book ai didi

python - 在数据帧中使用带有 lambda 表达式的条件时出现 "ValueError: The truth value of a Series is ambiguous"

转载 作者:行者123 更新时间:2023-11-30 22:29:51 27 4
gpt4 key购买 nike

我有一个数据框:dt以及列名称的列表:nn_language

编辑:添加示例数据

dt = pd.DataFrame({"language1": ["english", "english123", "ingles", "ingles123", "14.0", "13", "french"],
"language2": ["englesh", "english123", "ingles", "ingles123", "14", "13", "french"]})
nn_language = dt.columns[dt.columns.str.contains("language")]

dt[nn_language] 的所有元素都是 object 类型。我想做的是将 dt[nn_language] 的初始值更改为 "english" 如果初始值是 like ("english","ingles",14) 否则我想将初始值更改为 "other"

我尝试过:dt[nn_language].apply(lambda x: 'english' if x.str.contains('^engl|^ingl|14.0') else 'other')

但我收到错误 ValueError: ('系列的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all ().',

Thisthis没有帮助我

最佳答案

使用isin :

check = ["english","ingles", '14']
dt[nn_language].apply(lambda x: np.where(x.isin(check) , 'english', 'other'))

或者:

dt[nn_language].apply(lambda x: pd.Series(np.where(x.isin(check) , 'english', 'other')))

看来你需要:

dt[nn_language].apply(lambda x: np.where(x.str.contains('^engl|^ingl|14.0')  , 'english', 'other'))

关于python - 在数据帧中使用带有 lambda 表达式的条件时出现 "ValueError: The truth value of a Series is ambiguous",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46218134/

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