Python中的CountIfs

问题描述

我目前正在尝试将以下内容从Excel复制到Python:

IF(COUNTIFS(W4,“ multif ”,V4,“ 对话”)+ COUNTIFS(W4,“ ETF ”,V4 ,“ 对话”),1,0)

我可以使用以下代码执行COUNTIFS之一(这将是COUNTIFS(W4,“ multif ”,V4,“ 对话”)部分):

def countifs2(df,col,parameter,col2,parameter2,new_name):
df[new_name] = 0
df.loc[df[col].str.contains(parameter,na=True)
       & df[col2].str.contains(parameter2,na=True),new_name] = 1
return df

如何创建早期的Excel函数的副本,在其中查看两个COUNTIFS,如果其中一个为true,则返回1?

我当前的代码是:

def ORcountifs2(df,col3,parameter3,col4,parameter4,new_name):
df[new_name] = 0
df.loc[[df[col].str.contains(parameter,na=True)
       and df[col2].str.contains(parameter2,na=True)] 
       or 
       [df[col3].str.contains(parameter3,na=True)
       and df[col4].str.contains(parameter4,na=True)],new_name] = 1
return df

Excel中的示例:

enter image description here

如果(列B包含“ hello”,列C包含“ bat”)或(列B包含“ hel”,列D包含“ df”)

由于第一行满足OR语句的第二部分,因此此新列将为True,False,False。

谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)