Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over first N rows in pandas

Tags:

python

pandas

What is the suggested way to iterate over the rows in pandas like you would in a file? For example:

LIMIT = 100
for row_num, row in enumerate(open('file','r')):
    print (row)
    if row_num == LIMIT: break

I was thinking to do something like:

for n in range(LIMIT):
    print (df.loc[n].tolist())

Is there a built-in way to do this though in pandas?

like image 441
David542 Avatar asked Dec 20 '18 16:12

David542


People also ask

How do you get first 10 rows in pandas?

You can use df. head() to get the first N rows in Pandas DataFrame. Alternatively, you can specify a negative number within the brackets to get all the rows, excluding the last N rows.

How do you get top 5 rows in pandas?

pandas.DataFrame.head() In Python's Pandas module, the Dataframe class provides a head() function to fetch top rows from a Dataframe i.e. It returns the first n rows from a dataframe. If n is not provided then default value is 5.

How to iterate over rows in pandas Dataframe?

Let’s see the Different ways to iterate over rows in Pandas Dataframe : Method #1 : Using index attribute of the Dataframe . Method #2 : Using loc [] function of the Dataframe. Method #3 : Using iloc [] function of the DataFrame.

How to iterate over rows in Python?

In order to iterate over rows, we can use three function iteritems (), iterrows (), itertuples () . These three function will help in iteration over rows. In order to iterate over rows, we apply a iterrows () function this function return each index value along with a series containing the data in each row.

How to get the first n items from iterrows in pandas?

You have values, itertuples and iterrows out of which itertuples performs best as benchmarked by fast-pandas. Show activity on this post. You can use iterools.islice to take the first n items from iterrows: import itertools limit = 5 for index, row in itertools.islice (df.iterrows (), limit): ... Show activity on this post.

How to access different rows in a for loop in pandas?

We can use the Pandas .iloc accessor to access different rows while looping over the length of the for loop. Let’s see what this method looks like in Python: You could also access just a column, or a set of columns, by not just using the :.


1 Answers

Hasn't anyone answered the simple solution?

for row in df.head(5).itertuples():
    # do something

Take a peek at this post.

like image 107
knh190 Avatar answered Sep 27 '22 22:09

knh190