熊猫数据框条件计数

时间:2020-04-26 07:41:56

标签: python pandas

np.random.seed(2020)

df = (pd.DataFrame(np.random.rand(20, 5), columns=['Block','A','B','C','D'])
        .sort_values('Block'))
df['Block'] = df['Block'].mul(10).astype(int)
df.iloc[:, 1:] -= 0.7
print (df)
    Block         A         B         C         D
17      0  0.171687  0.202407 -0.250796 -0.081818
13      0  0.194283  0.131532  0.037843  0.198497
11      0 -0.135680  0.236032  0.103028 -0.002695
2       1  0.057080  0.036325 -0.344337 -0.358907
9       1 -0.063106 -0.144304 -0.508071 -0.274344
6       1  0.196258 -0.326606 -0.320307  0.158317
1       2 -0.423523 -0.356684  0.162159 -0.543300
14      2 -0.520039 -0.085842 -0.683331 -0.400678
19      2  0.232328 -0.286770 -0.539322 -0.231197
8       4  0.131468  0.063921  0.219691 -0.629427
12      4 -0.037565  0.049666 -0.168545 -0.217190
10      5 -0.430622 -0.100980 -0.479826 -0.399138
16      5 -0.522721  0.294459 -0.582625  0.140845
7       6 -0.116538 -0.031650 -0.522207  0.149248
3       6 -0.482899 -0.138573 -0.575821 -0.380264
5       6 -0.665809 -0.243881 -0.544149 -0.223951
15      6  0.252552  0.116207 -0.622138 -0.565387
4       9 -0.562643 -0.130587  0.275665 -0.196633
18      9 -0.302722 -0.252769 -0.466740  0.231729
0       9  0.173392 -0.190254 -0.428164 -0.363081

我要计算按“块”列分组的值> 0的单元格总数。

1 个答案:

答案 0 :(得分:0)

将列1903转换为以DataFrame.set_index进行索引,以DataFrame.gt进行比较,以更像Block,转换为整数,最后对每个索引使用0:< / p>

sum