Skip to main content
 首页 » 编程设计

python之如何为 Pandas 使用多个 if 条件

2025年05月04日13lautakyan007

我试图在我的 pandas 中使用多个条件,但出现以下错误:

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

根据这个thread我用按位运算符替换了 和 ,但我仍然收到错误。

import pandas as pd 
 
d1 = {'Year': [2019,2019,2019,2019,2019], 'Week':[1,2,4,6,7], 'Value':  
[20,40,60,75,90]} 
 
df1 = pd.DataFrame(data=d1) 
 
if (df1['Year'] == df1['Year'].shift(-1)) & \ 
 (df1['Week'] == df1['Week'].shift(-1)): 
    print('Yes') 
else: 
    print('No') 

我在这里做错了什么?

请您参考如下方法:

实际的比较检查并没有错,但不适用于常规的 Python if,因为 Pandas 以矢量化方式工作。正如我在关于错误的评论中所说:

What should Python say to if [1, 2, 3] and [2, 3, 4]:? That'd be True but it wouldn't tell you anything about individual rows (values in the list)

相反,使用 np.where .

df1['comparison'] = np.where((df1['Year'] == df1['Year'].shift(-1)) &  
                             (df1['Week'] == df1['Week'].shift(-1)), 'Yes', 'No')