在Python数据框中删除不需要的列

我是python / panda的新手。此数据框是实验室练习的一部分。

以下是数据框。结果有20行和384列。

           country almond angelica anise anise_seed apple apple_brandy /
55620  Switzerland     No       No    No         No    No           No   
55621  Switzerland    Yes       No    No         No   Yes           No   
55622  Switzerland     No       No    No         No    No           No   
55623  Switzerland     No       No    No         No    No           No   
55624  Switzerland     No       No    No         No    No           No   
55625  Switzerland     No       No    No         No    No           No   
55626  Switzerland     No       No    No         No    No           No   
55627  Switzerland     No       No    No         No    No           No   
55628  Switzerland    Yes       No    No         No    No           No

我想删除value为“ No”的所有列,并创建不包含这些列的该数据框的子集。根据以上数据集,这意味着只有“杏仁”和“苹果”列具有“否”以外的值。因此子集应该看起来像

           country almond apple 
55620  Switzerland     No    No
55621  Switzerland    Yes   Yes
55622  Switzerland     No    No
55623  Switzerland     No    No
55624  Switzerland     No    No
55625  Switzerland     No    No
55626  Switzerland     No    No
55627  Switzerland     No    No   
55628  Switzerland    Yes    No
评论
  • FBI
    FBI 回复

    First check by eq for equality and then test if at least one matched value in DataFrame.any:

    df = df.loc[:, df.ne('No').any()]
    print (df)
               country almond apple
    55620  Switzerland     No    No
    55621  Switzerland    Yes   Yes
    55622  Switzerland     No    No
    55623  Switzerland     No    No
    55624  Switzerland     No    No
    55625  Switzerland     No    No
    55626  Switzerland     No    No
    55627  Switzerland     No    No
    55628  Switzerland    Yes    No