Iterate over pandas series

Question:

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?

Asked By: Alan

||

Answers:

pandas >= 1.5

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

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

On older versions of pandas (< 1.5), this used to be 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.

Answered By: cs95
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.