【问题标题】:Remove more than one row at random from a pandas dataframe with an exception从熊猫数据框中随机删除多行,但有异常
【发布时间】:2017-10-24 22:50:57
【问题描述】:

我正在尝试从 df 中删除 xrows,但某个 row 除外。

df:

                  Main             Ing 
0                  A              Apple            
1                  B              Bread            
2                  Z              Cheese            
3                  E              Egg            
4                  D              Dough           
5                  X              Pasta  
etc. 

我尝试了以下操作,目的是删除一个row

r = randint(0, df.shape[0])
df.drop(df.index[r])

但是,它似乎什么也没做。

我的目标是从df中随机删除x数量的rows,除了某个row,例如:

df.loc[df['Main'] == 'A']


期望的输出:

例如:如果要删除的rows 的数量是4,除了row - df.loc[df['Main'] == 'A'],输出将是:

                  Main             Ing 
0                  A              Apple                      
2                  Z              Cheese                                
etc. 

【问题讨论】:

    标签: python python-2.7 pandas random


    【解决方案1】:

    使用pd.DataFrame.sample

    df.drop(df[df.Main != 'A'].sample(4).index)
    
      Main     Ing
    0    A   Apple
    2    Z  Cheese
    

    【讨论】:

    • 谢谢!那太棒了。 .index 的目的是什么?
    • pd.DataFrame.drop 将删除由传递的索引名称指定的行。 pd.DataFrame.sample 随机选择了 4 行,所以我传递了这些行的索引,以便 drop 做它的事情。
    【解决方案2】:

    从 1 : n 随机选取索引(PS:index = 0 是你要保留的行)

    import random
    df.drop(random.sample(range(1, df.shape[0]), 4),0)
    
    Out[212]: 
      Main    Ing
    0    A  Apple
    4    D  Dough
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-09
      • 1970-01-01
      • 2018-02-24
      • 2020-07-26
      • 1970-01-01
      • 2021-11-03
      • 2018-01-02
      • 2018-09-05
      相关资源
      最近更新 更多