gpt4 book ai didi

python-3.x - 删除 panda 中少于 3 个非零值的行

转载 作者:行者123 更新时间:2023-12-01 16:36:04 26 4
gpt4 key购买 nike

我想从 panda DataFrame 中删除少于 3 个非零值的行(不包括总列)。

所以现在我已经。

    year    2001 2002 2003 2004 2005 2006 2007 TOTAL
player
Emma 0 0 0 0 3 4 5 12
Max 3 5 0 0 0 0 0 8
Josh 1 2 4 1 2 1 0 11
Steve 0 0 0 0 3 0 0 3
Mike 1 0 0 0 0 0 2 3

但我想要:

    year    2001 2002 2003 2004 2005 2006 2007 TOTAL
player
Emma 0 0 0 0 3 4 5 12
Josh 1 2 4 1 2 1 0 11

我正在考虑使用 for 循环,但我不确定如何实现它/它是否是解决我的问题的最佳方法。

最佳答案

Pandas
drop TOTALsum 每行的非零数

df[df.drop('TOTAL', 1).ne(0).sum(1).gt(2)]

year 2001 2002 2003 2004 2005 2006 2007 TOTAL
player
Emma 0 0 0 0 3 4 5 12
Josh 1 2 4 1 2 1 0 11

numpy
更快的解决方案

v = df.values
m = (v[:, :-1] != 0).sum(1) > 2
pd.DataFrame(v[m], df.index[m], df.columns)

year 2001 2002 2003 2004 2005 2006 2007 TOTAL
player
Emma 0 0 0 0 3 4 5 12
Josh 1 2 4 1 2 1 0 11

关于python-3.x - 删除 panda 中少于 3 个非零值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43906035/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com