首页 > 解决方案 > 最小值给出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

标签: python-3.xpandas

解决方案


试试这个:

df.select_dtypes(include=np.number).min(axis=1).clip(upper=2)

如果只需要两列:

cols = ['value1','value2']
df[cols].min(axis=1).clip(upper=2)

推荐阅读