Skip to main content
 首页 » 编程设计

python之pandas add columns ,注意 Series 的真值不明确

2025年05月04日13dyllove98

我想在数据框 a 中添加一列,

a = pd.DataFrame([[1,2],[3,4]],columns=['A','B']) 
if a['B'] > a['A']: 
    a['C']='是' 
else: 
    a['C']='否' 

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

请您参考如下方法:

使用numpy.where :

#swapped 2,1 
a = pd.DataFrame([[2,1],[3,4]],columns=['A','B']) 
a['C'] = np.where(a['B']>a['A'], '是','否') 
print (a) 
   A  B  C 
0  2  1  否 
1  3  4  是 

如果使用,您的代码有问题:

print (a['B']>a['A']) 
0    False 
1     True 
dtype: bool 

它返回 bool 掩码,if 无法决定要做什么。

同时检查 using if truth statements with pandas .