2018年3月8日 星期四

[ Python 常見問題 ] Pandas - How to iterate over rows in a DataFrame in Pandas?

Source From Here 
Question 
I have a DataFrames from pandas: 
  1. import pandas as pd  
  2. inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}]  
  3. df = pd.DataFrame(inp)  
  4. print df  
Output: 
c1 c2 
0 10 100 
1 11 110 
2 12 120

Now I want to iterate over the rows of the above frame. For every row I want to be able to access its elements (values in cells) by the name of the columns. 

How-To 
iterrows is a generator which yield both index and row: 
>>> import pandas as pd 
>>> inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}] 
>>> df = pd.DataFrame(inp) 
>>> for i, row in df.iterrows(): 
... print("Row-{}: c1={}, c2={}".format(i, row['c1'], row['c2'])) 
... 
Row-0: c1=10, c2=100 
Row-1: c1=11, c2=110 
Row-2: c1=12, c2=120


沒有留言:

張貼留言

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