【问题标题】:Python - Pandas: IF statement based on column valuesPython - Pandas:基于列值的 IF 语句
【发布时间】:2020-07-09 21:14:56
【问题描述】:

我正在尝试开发一个 IF 语句,它将 - 如果 [Column Name] 中的值为零,则运行另一个 python 脚本。 - 否则什么都不做。

我最初的想法是做类似的事情

如果 df['列名'] == 0:

subprocess.call("python script.py", shall = True)

其他:

print('No values of 0')

这给了我以下错误:ValueError:一个系列的真值是不明确的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

如果我尝试指定其中任何一个,我并没有真正得到我想要的。

具体来说,我希望脚本遍历特定列的值,并查看这些值是否为 = 0,如果它们是,我想运行另一个向我发送电子邮件警告的脚本。

对不起,如果这已经在其他地方解释过,但我找不到它。

我在 Python 3.7.5 和使用 pandas。

感谢您的帮助

【问题讨论】:

标签: python pandas if-statement run-script


【解决方案1】:

如果任何值等于 0,您需要使用 .any 来计算整个系列,因为您希望它等于 True

df = pd.DataFrame({'count' : [0,1,2,3]})

print(df)

   count
0      0
1      1
2      2
3      3

if df['count'].eq(0).any():
    print('do sth')
else:
    print('pass')

out:

do sth

【讨论】:

    【解决方案2】:

    我这里有两个可能对你有帮助的 sn-ps:

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame()
    df['Random_Numbers'] = np.random.randn(10)
    

    第一个选项:

    # First: filter the list, check if it's empty, send a single email. 
    
    if df[df['Random_Numbers'] > 0.0].empty == False:
        print('Sending Email....Email Sent')
    

    输出:

    "Sending Email....Email Sent"
    
    ------------------------------------------------------------------------------
    

    第二个选项:

    # Second: iterate over each row in the dataframe, like you mentioned, check the value, send an email zero to multiple times. 
    
    for index, row in df.iterrows():
        if row['Random_Numbers'] > 0.0:
            print('Sending Email...Email Sent')  
    

    输出:

    "Sending Email...Email Sent"
    "Sending Email...Email Sent"
    "Sending Email...Email Sent"
    "Sending Email...Email Sent"
    "Sending Email...Email Sent"
    

    【讨论】:

    • 谢谢你第二次迭代成功了,但也花了一些时间 :) 我最终接受了 DataNovice 的建议,它完成得更快。
    猜你喜欢
    • 2018-09-26
    • 2018-09-20
    • 2019-05-01
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    相关资源
    最近更新 更多