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

Time:10-01

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".

CodePudding user response:

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
  • Related