Skip to main content
  1. About
  2. For Teams
Asked
Viewed 3k times
-1

There have been no questions which addressed this specific point:

I want to iterate through the rows of a dataframe. Specifically, within each row, I would like to call by column name. Is there a way to do this? If so, please demonstrate.

I am familiar with the df[<column_name>][<index_name>], but I don't think this addresses things. Perhaps I can mix this with the transpose function, but then I lose track of datatypes, right?

For example, if we have

    a b c d
 i1 1 1 2 1
 i2 2 2 1 1

I want to be able to say:

for f in some_iterator():
    print 'a is ' str(f['a'])
    print f['b'] + f['c']
    #skip f['d']

But as it stands, I can't depend on the column names, in this case, "a,b,c,d" to do this.

8
  • What do you mean "call by column name"? Does iterrows not do what you want?
    BrenBarn
    –  BrenBarn
    2014-10-22 23:31:19 +00:00
    Commented Oct 22, 2014 at 23:31
  • it doesn't. it seems to spit things out in a tabular format.
    user3659451
    –  user3659451
    2014-10-22 23:51:31 +00:00
    Commented Oct 22, 2014 at 23:51
  • As opposed to what? DataFrames are inherently tabular. Please clarify what you actually want to do.
    BrenBarn
    –  BrenBarn
    2014-10-23 00:34:39 +00:00
    Commented Oct 23, 2014 at 0:34
  • hope that clears things up? thanks @BrenBarn
    user3659451
    –  user3659451
    2014-10-23 00:41:53 +00:00
    Commented Oct 23, 2014 at 0:41
  • iterrows does do that, you just have to use the second element of each tuple that it yields. (And you need to do f['a'], not f[a]. There's no way that f[a] can work.)
    BrenBarn
    –  BrenBarn
    2014-10-23 00:43:35 +00:00
    Commented Oct 23, 2014 at 0:43

1 Answer 1

1

Let df be a pandas.DataFrame object.

We can iterate through the rows by:

for row in df.iterrows():
    print str(row[0]) + " is the index of the row"
    print str(row[1]) + " is a series with rows having \
    labels the same as the columns of the dataframe"
Sign up to request clarification or add additional context in comments.

1 Comment

Note that you can also do for index, row in df.iterrows() and get the index and row separately without having to access them by index.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.