Panda .loc or .iloc to select the columns from a dataset

前端 未结 2 1569
暗喜
暗喜 2020-12-19 15:08

I have been trying to select a particular set of columns from a dataset for all the rows. I tried something like below.

train_features = train_df.loc[,[0,4,5         


        
2条回答
  •  眼角桃花
    2020-12-19 15:19

    If need select by positions use iloc:

    train_features = train_df.iloc[:, [0,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]]
    print (train_features)
       age  default  housing  loan  equities  contact  duration  campaign  pdays  \
    0   56        1        1     1         1        0       261         1    999   
    1   37        1        0     1         1        0       226         1    999   
    2   56        1        1     0         1        0       307         1    999   
    
       previous  poutcome  emp.var.rate  cons.price.idx  cons.conf.idx  euribor3m  \
    0         0         2           1.1          93.994          -36.4   3.299552   
    1         0         2           1.1          93.994          -36.4   0.743751   
    2         0         2           1.1          93.994          -36.4   1.282652   
    
       nr.employed  
    0         5191  
    1         5191  
    2         5191  
    

    Another solution is drop unnecessary columns:

    cols= ['job','marital','education','y']
    train_features = train_df.drop(cols, axis=1)
    print (train_features)
       age  default  housing  loan  equities  contact  duration  campaign  pdays  \
    0   56        1        1     1         1        0       261         1    999   
    1   37        1        0     1         1        0       226         1    999   
    2   56        1        1     0         1        0       307         1    999   
    
       previous  poutcome  emp.var.rate  cons.price.idx  cons.conf.idx  euribor3m  \
    0         0         2           1.1          93.994          -36.4   3.299552   
    1         0         2           1.1          93.994          -36.4   0.743751   
    2         0         2           1.1          93.994          -36.4   1.282652   
    
       nr.employed  
    0         5191  
    1         5191  
    2         5191  
    

提交回复
热议问题