简体   繁体   中英

counifs Excel to Python Formula

Excel formula
=countif(C:L,"<=100" , C:L,">0")
Trying to count cells where it's value <=100 and is >0 (or != 0)

I was able to get somewhere near using iloc to group columns, then filter as following, then count, but seems I'm getting into deep mud, so here I am x(

columns=(filteredbyABArank.iloc[:, [2, 3, 4,5,6,7,8,9,10,11]]<=100) & (filteredbyABArank.iloc[:, [2, 3, 4,5,6,7,8,9,10,11]]>0)
columns.count()

The only way found was using a for loop, and doing it one row at a time, As there is no easy way to do "countif" on python, but using forloop

You can use an np.select() to find where the column is >0 or <= 100

condition_list = [(df['Column2'] > 0) & (df['Column2'] <= 100)]
choice_list = [1]
df['Count Column'] = np.select(condition_list, choice_list, 0)
print(df['Count Column'].sum())

Seeing your updated question I see you want to target 10 columns specifically. You can use this updated option with the np.select() to make it more dynamic and expandable

column_list = ['Column1', 'Column2']
for i in range(0, len(column_list)):
    condition_list = [(df[column_list[i]] > 0) & (df[column_list[i]] <= 100)]
    choice_list = [1]
    new_column__count = f'Count Column {column_list[i]}'
    df[new_column__count] = np.select(condition_list, choice_list, 0)
df

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