Skip to main content
Engineering LibreTexts

14.4: Iterating Through the Values of a Series

  • Page ID
    39295
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    Great news: if you mastered the previous section, this one and the next will be a snap. That’s because Python, NumPy, and Pandas work together to make iterating through a Series pretty much exactly the same as iterating through an array. In fact, sometimes you’re not even sure which type you’ve got!

    Here’s the Marvel Series regurgitated yet again:

    Code \(\PageIndex{1}\) (Python):

    alter_egos = pd.Series(['Hulk','Spidey','Iron Man','Thor'], index=['Bruce','Peter','Tony','Thor'])

    Let’s say I want to go through and greet all our heroes. It’s a snap! (no pun intended):

    Code \(\PageIndex{2}\) (Python):

    print("Welcome to the Marvel Cinematic Universe(tm).") for hero in alter_egos:

    print("Greetings, {}!".format(hero))

    print("Go team!")

    | Welcome to the Marvel Cinematic Universe(tm).

    | Greetings, Hulk!

    | Greetings, Spidey!

    | Greetings, Iron Man!

    | Greetings, Thor!

    | Go team!

    What could be easier?

    Notice that “looping through the Series” effectively means “looping through the values of the Series,” not the keys. What if we want to loop through the keys instead?


    This page titled 14.4: Iterating Through the Values of a Series is shared under a CC BY-SA 4.0 license and was authored, remixed, and/or curated by Stephen Davies (allthemath.org) via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.