2021年1月9日 星期六

[ 常見問題 ] How to select all columns, except one column in pandas?

 Source From Here

Question
I have a dataframe look like this:
  1. import pandas  
  2. import numpy as np  
  3. df = DataFrame(np.random.rand(4,4), columns = list('abcd'))  
  4. df  
  5.       a         b         c         d  
  6. 0  0.418762  0.042369  0.869203  0.972314  
  7. 1  0.991058  0.510228  0.594784  0.534366  
  8. 2  0.407472  0.259811  0.396664  0.894202  
  9. 3  0.726168  0.139531  0.324932  0.906575  

How I can get all columns except column b?

HowTo
When the columns are not a MultiIndexdf.columns is just an array of column names so you can do:
  1. df.loc[:, df.columns != 'b']  
  2.   
  3.           a         c         d  
  4. 0  0.561196  0.013768  0.772827  
  5. 1  0.882641  0.615396  0.075381  
  6. 2  0.368824  0.651378  0.397203  
  7. 3  0.788730  0.568099  0.869127  
Or you can leverage API:difference:
  1. df[df.columns.difference(['b'])]  
  2.   
  3. Out:   
  4.           a         c         d  
  5. 0  0.427809  0.459807  0.333869  
  6. 1  0.678031  0.668346  0.645951  
  7. 2  0.996573  0.673730  0.314911  
  8. 3  0.786942  0.719665  0.330833  


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...