Python-Pandas:IF语句基于列值



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

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

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

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

其他:

print('No values of 0')

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

如果我试图具体说明其中的任何一个,我并没有真正得到我想要的。

具体来说,我希望脚本迭代特定列的值,看看这些值中是否有任何一个=0,如果是,我想运行另一个脚本,它会向我发送电子邮件警告。

很抱歉,如果这已经在其他地方解释过了,但我找不到。

我在Python 3.7.5和使用pandas。

感谢的帮助

如果任何值等于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

我这里有两个片段可能会对您有所帮助:

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"

最新更新