简体   繁体   English

将 Excel 转换为 Python 公式

[英]counifs Excel to Python Formula

Excel formula Excel公式
=countif(C:L,"<=100" , C:L,">0")
Trying to count cells where it's value <=100 and is >0 (or != 0)尝试计算其值 <=100 且 >0(或!= 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(我能够使用 iloc 对列进行分组,然后按以下方式过滤,然后计数,但似乎我陷入了深泥中,所以我在这里 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找到的唯一方法是使用 for 循环,一次做一行,因为在 python 上没有简单的方法来执行“countif”,而是使用 forloop

You can use an np.select() to find where the column is >0 or <= 100您可以使用 np.select() 来查找列的位置 >0 或 <= 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.看到您更新的问题,我看到您想专门针对 10 列。 You can use this updated option with the np.select() to make it more dynamic and expandable您可以将此更新选项与 np.select() 一起使用,使其更具动态性和可扩展性

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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