简体   繁体   中英

Pandas - Multiple criteria Countifs row by row

I have this dataframe: 数据框

In excel I have the simple count if =if((COUNTIFS(B:B,B2,A:A,"=A"))=0,"No","Yes")

So essentially, how do I loop through all of the rows, countif the Cell in MatchID against Range(MatchID) AND if Range(provider) = "A".

Whilst recording the entry in a new column.

Simply enough to do in VBA and excel but python/Pandas is new to me and still slightly beyond my mental grasp.

Is this possible?

Thanks for any help.

Here is a vectorised solution. In general, try and use a set for comparisons and in-built pandas functionality such as map / isin . This not only is more efficient, but more readable.

filter_set = set(df.loc[df['Provider']=='A', 'MatchID'])  # set of MatchIDs with Provider 'A'

df['Solution'] = df['MatchID'].isin(filter_set).map({True: 'Yes', False: 'No'})

This code will help.

#create dataframe object
#consider it as df

check = (df['MatchID'] > 'yourmatchId') & (a['provider'] <"A")
df["NewColumn"] = df[check]['YourRequiredColumn']

You can go about that like this:

cond_list = df.loc[df['Provider']=='A', 'MatchID'].tolist() #list of MatchIDs that have Provider with value 'A'

df['Solution'] = df['MatchID'].apply(lambda x: 'Yes' if x in cond_list else 'No')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM