2020年10月31日 星期六

[ Python 常見問題 ] How do I insert a column at a specific column index in pandas?

 Source From Here

Question
Can I insert a column at a specific column index in pandas?
  1. import pandas as pd  
  2. df = pd.DataFrame({'l':['a','b','c','d'], 'v':[1,2,1,2]})  
  3. df['n'] = 0  

This will put column n as the last column of df, but isn't there a way to tell df to put n at the beginning?

HowTo
see docs: http://pandas.pydata.org/pandas-docs/stable/genera...d/pandas.DataFrame.insert.html

using loc = 0 will insert at the beginning:
  1. df.insert(loc, column, value)  
For example:
  1. df = pd.DataFrame({'B': [123], 'C': [456]})  
  2.   
  3. df  
  4. Out:   
  5.    B  C  
  6. 0  1  4  
  7. 1  2  5  
  8. 2  3  6  
  9.   
  10. idx = 0  
  11. new_col = [789]  # can be a list, a Series, an array or a scalar     
  12. df.insert(loc=idx, column='A', value=new_col)  
  13.   
  14. df  
  15. Out:   
  16.    A  B  C  
  17. 0  7  1  4  
  18. 1  8  2  5  
  19. 2  9  3  6  

沒有留言:

張貼留言

[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...