python-3.x - 最小值给出ValueError:Series的真值不明确
问题描述
我希望使用下面的代码来计算一个名为 min 的字段,它是 value 2
、 fieldvalue1
和 field的最小值value2
import pandas as pd
import numpy as np
df=pd.DataFrame({"value1":[3,2,1],"value2":[3,2,3],"value3":[1,1,1]})
如果我使用
df["min"]=min(2,df['value1'],df['value2'])
我得到了错误
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
预期的输出是:
value1 value2 value3 min
0 3 3 1 2
1 2 2 1 2
2 1 3 1 1
解决方案
试试这个:
df.select_dtypes(include=np.number).min(axis=1).clip(upper=2)
如果只需要两列:
cols = ['value1','value2']
df[cols].min(axis=1).clip(upper=2)
推荐阅读
- lucene - 什么是相当于 SQL `IS NULL OR someDate > GETDATE()` 的 Lucene 查询?
- r - 在R RStudio中选择一列的两个特定值
- javascript - 为什么单击按钮时值不会增加或减少
- sql - SQL查询将每个值的列格式更改为行
- javascript - 当机器人响应并且用户想要继续时,如何让机器人回答用户,就像对话一样(但不重复)
- javascript - 如何在 Electron 应用程序中激活 Ctrl+F 研究快捷键?
- c++ - 如何获取 std::set 指针中的第一个元素,其中指针指向特定值?
- web-scraping - 下载复杂的 3D JS/Canvas 网页以供离线使用
- python - python从包含特定表达式的字符串中删除特定行
- ios - 使用 Swift 在 tableview 中使用 headers 部分进行复制