Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over pandas series

I want to travel round the series index

In [44]: type(ed1)
Out[44]: pandas.core.series.Series

In [43]: for _, row  in ed1.iterrows():
...:     print(row.name)

and I get this error:

  AttributeError: 'Series' object has no attribute 'iterrows'

Does series has any methods like iterrows?

like image 459
Alan Avatar asked May 10 '18 06:05

Alan


People also ask

Can you iterate over pandas series?

iteritems() function iterates over the given series object. the function iterates over the tuples containing the index labels and corresponding value in the series.

Can we use S Iteritems () on a PD series object's to iterate on it?

We can use s. iteritems() on a pd. Series objects to iterate on it. loc and iloc are two useful and commonly used Pandas methods.


1 Answers

Series objects define an iteritems method (the data is returned as a iterator of index-value pairs.

for _, val in ed1.iteritems():
    ...

Alternatively, you can iterate over a list by calling tolist,

for val in ed1.tolist():
    ...

Word of advice, iterating over pandas objects is generally discouraged. Wherever possible, seek to vectorize. To that end, I recommend taking a look at my answer to How to iterate over rows in a DataFrame in Pandas? which discusses better alternatives to iteration.

like image 160
cs95 Avatar answered Oct 04 '22 19:10

cs95