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

标签 python pandas lambda

我有一个数据框: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/

相关文章:

python - 如何通过 Python 使用 Selenium 在 invisibility_of_element_located 上等待多个条件

python - 两个 DataFrames (Python/Pandas) 中每一行和每一列的区别

lambda - 将函数作为参数传递给另一个函数

c# - 仿函数什么时候应该使用它们它们的预期用途是什么

python - 有没有更好的方法来使用 Python 的 typing 模块为复合类型创建类型别名?

python - 创建对象并将用户定义的函数作为方法传递

python - pandas - 将包含字符串的列和包含 int 的列解析为日期时间

Python - 功能 "find"?

python 2.6 cPickle.load 导致 EOFError

python - 以类似枢轴的方式对分层数据进行排序