Skip to main content
 首页 » 编程设计

python之If, And Statement 没有在 Python 中输出准确的结果

2024年11月24日10arxive

df.loc[(df['Platform'] == 'A321') and (df['Days'] <= 14), 'Mods Applicable'] = 'CFM56 9th Stage Duct' 

我试图让 A321 的平台和天数小于或等于 14 的输出打印出以下“适用的模组”,但它没有输出平台和天数。

输出结果:

IF 和输出:

请您参考如下方法:

尝试使用“&”而不是“and”:

df = pd.DataFrame({'Platform': ['A123', 'A321', 'A321', 'B123'], 
                   'Days': [10, 13, 20, 5]}) 
 
df.loc[(df['Platform'] == 'A321') & (df['Days'] <= 14), 'Mods Applicable'] = 'CFM56 9th Stage Duct' 
 
print(df) 
 
      Platform  Days       Mods Applicable 
    0     A123    10                   NaN 
    1     A321    13  CFM56 9th Stage Duct 
    2     A321    20                   NaN 
    3     B123     5                   NaN 

我可以通过使用“and”而不是“&”来重现相同的错误:

Traceback (most recent call last): 
 
  File "<ipython-input-128-7957a219684b>", line 1, in <module> 
    df.loc[(df['Platform'] == 'A321') and (df['Days'] <= 14), 'Mods Applicable'] = 'CFM56 9th Stage Duct' 
 
  File "/Users/nathanielgates/anaconda3/lib/python3.6/site-packages/pandas/core/generic.py", line 1479, in __nonzero__ 
    .format(self.__class__.__name__)) 
 
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().