删除方差阈值下的熊猫df行

时间:2019-10-30 15:21:58

标签: python pandas variance

我的df如下所示(我是通过pivot_table获得的):

ID_column Test1 Test2 Test3 Test4
ID1       0     1     3     0
ID2       4     2     0     0
ID3       3     1     3     5

我想在计算的方差时删除所有落在方差阈值x以下的。我找不到任何地方,只有解决方案才能做到这一点。

1 个答案:

答案 0 :(得分:2)

您可以使用以下代码执行此操作:

threshold = 1 # define variance threshold    
row_vars = df.var(axis=1) # calculate variance over rows.

rows_to_drop = df[row_vars>threshold].index

# drop the rows in place
df.drop(rows_to_drop, axis=0, inplace=True)

总结:

以行方式计算方差,获取方差超过此阈值的行的索引,然后将其放在适当的位置。