If、And语句不能在Python中输出准确的结果

2024-05-13 21:00:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

输出结果:

Output results

如果(&A);输出:

IF & Output


Tags: andmodsdf平台daysstagelocplatform
2条回答

尝试使用“&;”而不是“和”:

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().

这是因为将Series与值进行比较也会返回Series。这意味着(df['Platform'] == 'A321')(df['Days'] <= 14)的结果是Seriestrue/false值的Series,默认情况下它不会解析为单个true或false。所以你不能and

可以用&替换and。所以它会变成:

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

相关问题 更多 >