Python 基于固定值删除列
我正在尝试删除非零小于所述数字的列。这是我得到的代码,但它给出了相同的答案。我做错了什么Python 基于固定值删除列,python,pandas,Python,Pandas,我正在尝试删除非零小于所述数字的列。这是我得到的代码,但它给出了相同的答案。我做错了什么 df = pd.DataFrame([[1,0,0,0], [0,0,1,0]]) 0 1 2 3 0 1 0 0 0 1 0 0 1 0 df = df.loc[:, (df.astype(bool).sum(axis=0) <= max_number_of_zeros)] 0 1 2 3 0 1 0 0 0 1 0 0 1 0
df = pd.DataFrame([[1,0,0,0], [0,0,1,0]])
0 1 2 3
0 1 0 0 0
1 0 0 1 0
df = df.loc[:, (df.astype(bool).sum(axis=0) <= max_number_of_zeros)]
0 1 2 3
0 1 0 0 0
1 0 0 1 0
对于值为2的列0和列2,输出为
0 1 2 3
0 1 0 0 0
1 2 0 1 0
2 0 2 3 4
3 1 1 1 1
我认为您需要将布尔掩码更改为
df.eq(0)
,这与df==0
相同,条件已从更改,答案是否应为col1和co2?@ubuntu\u noob-抱歉,解决方案已多次编辑,现在应该可以正常工作。对于零=2的数量,df不会更改是的,这是预期的,因为我想删除的列中有两个以上的零,所以这意味着有三个或更多我想删除的列中有两个以上的零
0 1 2 3
0 1 0 0 0
1 2 0 1 0
2 0 2 3 4
3 1 1 1 1
max_number_of_zeros = 2
df = df.loc[:,df.eq(0).sum(axis=0) < max_number_of_zeros]
print (df)
0 2
0 1 0
1 2 1
2 0 3
3 1 1
print (df.eq(0))
0 1 2 3
0 False True True True
1 False True False True
2 True False False False
3 False False False False
print (df.eq(0).sum(axis=0))
0 1
1 2
2 1
3 2
dtype: int64
max_number_of_zeros = 2
df = df.loc[:,len(df.columns) - df.astype(bool).sum(axis=0) < max_number_of_zeros]
print (df)
0 2
0 1 0
1 2 1
2 0 3
3 1 1