2

I am trying to find a way that gets the row of a dataframe using index that has the same result as using data_file.iterrows(). I tried the following code, but they are not indentical. Is there any way to do this? Thanks!

for row in data_file.iterrows():
    print(row == data_file.iloc[0])
    print(row)
    print(data_file.iloc[0])
    break
1
  • You should really be saying for ind, row in data_file.iterrows(): The iterator gives you a tuple of index, row Commented Feb 17, 2018 at 12:03

2 Answers 2

2

The corresponding series value is on index1, does that help?

Docs: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iterrows.html

DataFrame.iterrows()[source]

Iterate over DataFrame rows as (index,Series) pairs.

print(row[1] == data_file.iloc[0])

Another solution:

for ind, row in data_file.iterrows():
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks! but why it is row[1]?
@CongYang Because it is returned as a pair where you are looking for the 2nd element [1]. This: Iterate over DataFrame rows as (index,Series) pairs.
Because you should really be saying for ind, row in data_file.iterrows(): The iterator gives you a tuple of index, row
@smci Yeah well I agree. However I did link to the docs and the phrase: Iterate over DataFrame rows as (index,Series) pairs.
(Anton vBR, I was addressing that to the OP)
|
2

Because iterrows returns a tuple consisting of the index of the row and the row itself and iloc the row.

print(type(row))
<class 'tuple'>
print(type(pl0.iloc[0]))  
<class 'pandas.core.series.Series'>
print(type(row[1]))
<class 'pandas.core.series.Series'>

You may use python's ability to unpack tuples:

for index, row in data_file.iterrows():

Why are you not using iloc directly, anyway? Using iterrows is not recommended, because of its negative performance impact.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.