简体   繁体   English

计算指定列范围的所有行中的非 0 值 - Python Pandas

[英]Count Non 0 Values in all Rows for Specified Range of Columns - Python Pandas

What is the best approach for counting non-0 values in all rows for a specified range of columns?为指定范围的列计算所有行中的非 0 值的最佳方法是什么? My failed attempt below:我在下面的失败尝试:

data = [[2015, 900, 2016, 850, 900, 850, 1000, 0, 0, -50, 50, -1000, 0], 
        [2016, 500, 2017, 550, 0, 500, 550, 350, 0, 500, 50, -200, -350], 
        [2017, 200, 2018, 300, 0, 0, 200, 300, 100, 0, 200, 100, -200], 
        [2018, 775, 2019, 1000, 0, 0, 0, 775, 1000, 0, 0, 775, 225], 
        [2019, 30, 2020, 0, 0, 0, 0, 0, 30, 0, 0, 0, 30]] 
data = pd.DataFrame(data, columns = ['cohortYear', 'firstYearSales', 'firstFullYear', 'firstFullYearSales', '2015','2016','2017', '2018', '2019', '2016 Delta', '2017 Delta', '2018 Delta', '2019 Delta'])

countRange = data.columns[5:9]

data['activeYears'] = data[countRange].count(axis=1)
data

Try:尝试:

data['activeYears'] = (data[countRange] > 0).sum(axis=1)

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

相关问题 查找 pandas 中指定行范围之间的行数 - find the count of rows between the specified range of rows in pandas 在 Pandas Python 中检查所有列后删除没有值的行 - Drop rows with no values after checking all columns in Pandas Python Python / Pandas:删除具有外围值的行,并保留所有列 - Python/Pandas: Remove rows with outlying values, keeping all columns 遍历 Pandas DataFrame 中的行,删除特定字符串后指定列数内的所有值 - Iterate Over Rows in Pandas DataFrame Deleting All Values Within a Specified Number of Columns After a Specific String select pandas dataframe 中所有列的值范围 - select range of values for all columns in pandas dataframe 删除所有列中具有特定值的行 Pandas - Drop rows with specific values in all columns Pandas Pandas - 获取除一组列之外所有值为 null 的行数 - Pandas - Get count of rows where all values are null except for a set of columns 如何在python熊猫中计算行而不是值? - How to count rows not values in python pandas? 使用多列中的值进行过滤后,Python Pandas Dataframe获得行数 - Python Pandas Dataframe get count of rows after filtering using values from multiple columns Python Pandas:有效计算值大于或等于一组值的行数,按键列分组 - Python Pandas: Efficiently compute count of rows with value greater than or equal to a set of values, grouped by key columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM