Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if last row in pandas df.iterrows()

How can I check last row in Python pandas df.itterows() during its iteration?

My code :

for index, row in df.iterrows():
...     # I want to check last row in df iterrows(). somelike row[0].tail(1)
like image 974
Yuda Prawira Avatar asked May 14 '17 20:05

Yuda Prawira


People also ask

What does DF Iterrows () do?

Pandas DataFrame iterrows() Method The iterrows() method generates an iterator object of the DataFrame, allowing us to iterate each row in the DataFrame. Each iteration produces an index object and a row object (a Pandas Series object).

How do you get the last row in pandas?

Select & print last row of dataframe using tail() It will return the last row of dataframe as a dataframe object. Using the tail() function, we fetched the last row of dataframe as a dataframe and then just printed it.

How do I use Iterrows in pandas DataFrame?

iterrows() function in Python. Pandas DataFrame. iterrows() is used to iterate over a pandas Data frame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in form of series.

What is faster than Iterrows?

itertuples() takes 16 seconds to iterate through a data frame with 10 million records that are around 50x times faster than iterrows().


2 Answers

Use

for i, (index, row) in enumerate(df.iterrows()):
    if i == len(df) - 1:
        pass
like image 80
piRSquared Avatar answered Oct 13 '22 23:10

piRSquared


The pandas.DataFrame class has a subscriptable index attribute. So one can check the index of the row when iterating over the row using iterrows() against the last value of the df.index attribute like so:

for idx,row in df.iterrows():
    if idx == df.index[-1]:
        print('This row is last')
like image 43
Alexander Lobkovsky Meitiv Avatar answered Oct 13 '22 23:10

Alexander Lobkovsky Meitiv