2017-08-12 29 views
1

我有以下数据框:如何在数据框上逐个迭代项目?

          Date Price 
Equity(231 [IBM]) 2016-05-10 00:00:00+00:00 150.04 
Equity(2574 [TSLA]) 2016-04-29 00:00:00+00:00 248.43 

我尝试了数据帧使用迭代:

for row in df.itertuples(): 
    print("symbol :\n",row[0]) 
    print("Date :\n",row[1]) 
    print("Price :\n",row[2]) 

输出:

symbol : Equity(231 [IBM]) 
Date : 2016-05-10 00:00:00+00:00 
Price : 150.04 
symbol : Equity(2574 [TSLA]) 
Date : 2016-04-29 00:00:00+00:00 
Price : 248.43 

我不希望上面的输出,因为它遍历两个IBM和TSLA,而不是IBM。 我想下面的输出,当我们遍历:

Out: 

symbol : Equity(231 [IBM]) 
Date : 2016-05-10 00:00:00+00:00 
Price : 150.04 

并在接下来的迭代:

Out: 

symbol : Equity(2574 [TSLA]) 
Date : 2016-04-29 00:00:00+00:00 
Price : 248.43 

如果你仍然觉得很难理解,随意要求进一步澄清。

+0

你已经使用了一个for循环,它会遍历所有的df.rows(可以作为元组)直到最后一行,然后结束(我的意思是循环出来)。首先检查你是否真的需要for循环或对数据框的任何有条件的访问。 – Satya

回答

2

您可以使用DataFrame.itertuplesDataFrame.iterrows

for row in df.itertuples(): 
    print("symbol :",row.Index) 
    print("Date :",row.Date) 
    print("Price :",row.Price) 
    print ('***************************' 

symbol : Equity(231 [IBM])) 
Date : 2016-05-10 00:00:00+00:00 
Price : 150.04 
*************************** 
symbol : Equity(2574 [TSLA]) 
Date : 2016-04-29 00:00:00+00:00 
Price : 248.43 
*************************** 

for idx, row in df.iterrows(): 
    print("symbol :",idx) 
    print("Date :",row.Date) 
    print("Price :",row.Price) 
    print ('***************************') 

symbol : Equity(231 [IBM]) 
Date : 2016-05-10 00:00:00+00:00 
Price : 150.04 
*************************** 
symbol : Equity(2574 [TSLA]) 
Date : 2016-04-29 00:00:00+00:00 
Price : 248.43 
*************************** 
+0

我只想在第一次迭代中'IBM的属性和第二次迭代中的'TSLA' :) – ArJuN

+0

那就是你用代码得到的东西吗? – Dark

+0

这应该是你在你写的代码中得到的。 – AetherUnbound

0

如果你试过iterrows怎么办?

for index, row in df.iterrows(): 
    print("symbol :\n",row[0]) 
    print("Date :\n",row[1]) 
    print("Price :\n",row[2]) 
+0

'IndexError:索引超出范围' – ArJuN

1

尚未肯定,你想要什么,但低于尝试..

for idx in range(len(df)): 
    desired_row = df.ix[idx] #gets first row for 1st iteration as a series 
    print(desired_row) ###you can call any function as per requirement here. 

我可以如果你的审判没有错或在@ Jezrael的答案中,如果哟你想迭代数据帧。

+0

感谢您的答案,但它引发'TypeError:'DataFrame'对象不能被解释为一个整数' – ArJuN

+0

对不起,错字..看到更正的一个 – Satya

+0

好的,所有发布的答案都是正确的,但是我不明白'for loop'如何在元组上工作,所以这个混乱,无论如何。 – ArJuN