[英]Is there a way to calculate average with only values in the columns greater than 0 in dataframe?
Is there a way to calculate average with only values in the columns greater than 0 in dataframe?有没有办法在 dataframe 中仅使用大于 0 的列中的值来计算平均值? I have a dataset with the structure below.我有一个结构如下的数据集。
Week |Mon |Tues |Weds |Thurs |Fri |Sat |Sun |average
:-------:-------:-------:----------:-------:-------:--------:-------:-----------
1 |5915 |2997 |8499 |1248 |3089 |1343 |0 |3298.71
2 |0 |0 |3588 |5693 |1297 |288 |2453 |1902.71
Using mean will get all the values in the stated columns which gives Total/7.使用平均值将获得所述列中的所有值,即 Total/7。 df['average'] = df[['Mon', 'Tues','Weds','Thurs','Fri','Sat','Sun']].mean(axis=1)
Is there a way to get results in with the following:有没有办法通过以下方式获得结果:
Week |Mon |Tues |Weds |Thurs |Fri |Sat |Sun |average (desired output)
:-------:-------:-------:----------:-------:-------:--------:-------:--------------------------------
1 |5915 |2997 |8499 |1248 |3089 |1343 |0 |(5915+2997+8499+1248+3089+1343)/6
2 |0 |0 |3588 |5693 |1297 |288 |2453 |(3588+5693+1297+288+2453)/5
Just add another layer of boolean indexing to make it only positive numbers:只需添加另一层 boolean 索引,使其只有正数:
df[df[['Mon', 'Tues','Weds','Thurs','Fri','Sat','Sun']]>0].mean(axis=1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.