Get row item instead of index-# from iterrows()

Question:

I am new in Python, and trying to understand how the iterrows-function works in Pandas. I am trying to iterate over each row in the csv-file below and print the values in the name, month and day-columns. It works for all except for the name-column. Index-numbers are printed instead of "Brond" and "Birdie".

### Below is the content of a file named examples.csv:
name,email,year,month,day
Brond,[email protected],1985,09,30
Birdie,[email protected],1985,08,29

My attempt is:

with open("examples.csv") as examples_file:
examples = pandas.read_csv(examples_file)
for (index, row) in examples.iterrows():
    print(row.name)

### The printed result is "0" and "1", instead of "Brond" and "Birdie".
Asked By: mentace

||

Answers:

You should avoid using the attributes (row.name) and rather slice with indices (row['name']).

Using attributes has many pitfalls, you just fell in one! .name gives the Series name so if an indices name clashes, this doesn’t work.

for (index, row) in examples.iterrows():
    print(row['name'])

output:

Brond
Birdie
Answered By: mozway
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.