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


沒有留言:

張貼留言

[ Python 常見問題 ] Get all object attributes in Python?

Source From  Here   Question   Is there a way to  get all attributes/methods/fields/etc. of an object in Python ?  vars()  is close to what ...