在Pandas DataFrame中获取每行非零值的计数

6

我知道这是一个简单的问题,但我对Pandas非常陌生。 我想要比较每一行中的单元格,看看列中的任何单元格是否大于或小于0.00。

              GOOG    AAPL     XOM     IBM       Value
2011-01-10     0.0     0.0     0.0     0.0       0.00
2011-01-13     0.0 -1500.0     0.0  4000.0  -61900.00

我知道pandas有内置的iterrows方法。但是,使用以下代码时,我遇到了错误:

for index, row in dataFrame.iterrows():
    for i in range(0, len(of_columns)):
        print dataFrame[index][i]

错误

返回self._engine.get_loc(self._maybe_cast_indexer(key)) File "pandas\index.pyx",第132行,在pandas\index.c中,pandas.index.IndexEngine.get_loc File "pandas\index.pyx",第154行,在pandas\index.c中,pandas.index.IndexEngine.get_loc File "pandas\src\hashtable_class_helper.pxi",第732行,在pandas\hashtable.c中,pandas.hashtable.PyObjectHashTable.get_item File "pandas\src\hashtable_class_helper.pxi",第740行,在pandas\hashtable.c中,pandas.hashtable.PyObjectHashTable.get_item

预期操作 如果单元格包含0,则不执行任何操作(继续)。如果单元格包含非零值,则计算每行的非零值数量。

1个回答

13

使用gt>)、lt<)或legeneeq等进行比较,然后统计True的数量,步骤类似于1

不好 -> 检查所有先前的列:

df['> zero'] = df.gt(0).sum(axis=1)
df['< zero'] = df.lt(0).sum(axis=1)
df['== zero'] = df.eq(0).sum(axis=1)
print (df)
            GOOG    AAPL  XOM     IBM    Value  > zero  < zero  == zero
2011-01-10   0.0     0.0  0.0     0.0      0.0       0       0        7
2011-01-13   0.0 -1500.0  0.0  4000.0 -61900.0       1       2        2

正确 - 选择要检查的列:

cols = df.columns
df['> zero'] = df[cols].gt(0).sum(axis=1)
df['< zero'] = df[cols].lt(0).sum(axis=1)
df['== zero'] = df[cols].eq(0).sum(axis=1)
print (df)
            GOOG    AAPL  XOM     IBM    Value  > zero  < zero  == zero
2011-01-10   0.0     0.0  0.0     0.0      0.0       0       0        5
2011-01-13   0.0 -1500.0  0.0  4000.0 -61900.0       1       2        2

详细信息:

print (df.gt(0))
             GOOG   AAPL    XOM    IBM  Value
2011-01-10  False  False  False  False  False
2011-01-13  False  False  False   True  False

编辑:

要从“cols”中删除某些列,请使用difference函数:

cols = df.columns.difference(['Value'])
print (cols)
Index(['AAPL', 'GOOG', 'IBM', 'XOM'], dtype='object')

df['> zero'] = df[cols].gt(0).sum(axis=1)
df['< zero'] = df[cols].lt(0).sum(axis=1)
df['== zero'] = df[cols].eq(0).sum(axis=1)
print (df)
            GOOG    AAPL  XOM     IBM    Value  > zero  < zero  == zero
2011-01-10   0.0     0.0  0.0     0.0      0.0       0       0        4
2011-01-13   0.0 -1500.0  0.0  4000.0 -61900.0       1       1        2

很好的答案,但如果我想从计算中删除Value列怎么办?我该如何在cols = dataFrame.columns中删除它? - Fran Martinez
1
使用 cols = df.columns.difference(['Value']) - jezrael
我把它添加到答案中。 - jezrael
非常感谢您! - Fran Martinez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接