pandas: get the value of the index for a row?
<p>I have a dataframe:</p>

<pre><code>                 cost       month  para
prod_code
040201060AAAIAI    43  2016-01-01  0402
040201060AAAIAJ    45  2016-02-01  0402
040201060AAAIAI    46  2016-03-01  0402
040201060AAAIAI    41  2016-01-01  0402
040201060AAAIAI    48  2016-02-01  0402
</code></pre>

<p>How can I iterate over the rows, and get the value of the index for each one?</p>

<pre><code>d = { 'prod_code': ['040201060AAAIAI', '040201060AAAIAJ', '040201060AAAIAI', '040201060AAAIAI', '040201060AAAIAI', '040201060AAAIAI', '040301060AAAKAG', '040301060AAAKAK', '040301060AAAKAK', '040301060AAAKAX', '040301060AAAKAK', '040301060AAAKAK'], 'month': ['2016-01-01', '2016-02-01', '2016-03-01', '2016-01-01', '2016-02-01', '2016-03-01', '2016-01-01', '2016-02-01', '2016-03-01', '2016-01-01', '2016-02-01', '2016-03-01'], 'cost': [43, 45, 46, 41, 48, 59, 8, 9, 10, 12, 15, 13] }
df = pd.DataFrame.from_dict(d)
df.set_index('prod_code', inplace=True)
</code></pre>

<p>This is what I'm trying:</p>

<pre><code>for i, row in df.iterrows():
    print row.index, row['cost']
</code></pre>

<p>But I get this:</p>

<pre><code>Index([u'items', u'cost'], dtype='object') 3.34461552621
</code></pre>

<p>UPDATE: This is the same as asking how to get the name of the index for a series, but phrased differently. Also though the <em>answer</em> is the same as another question, the <em>question</em> is not the same! Specifically, this question will be found when people Google for "pandas index of row" rather than "pandas name of series". </p>

<pre><code>for i, row in df.iterrows():
</code></pre>

<p>returns a <code>Series</code> for each row where the <code>Series</code> name is the <code>index</code> of the row you are iterating through. you could simply do</p>

<pre><code>d = { 'prod_code': ['040201060AAAIAI', '040201060AAAIAJ', '040201060AAAIAI', '040201060AAAIAI', '040201060AAAIAI', '040201060AAAIAI', '040301060AAAKAG', '040301060AAAKAK', '040301060AAAKAK', '040301060AAAKAX', '040301060AAAKAK', '040301060AAAKAK'], 'month': ['2016-01-01', '2016-02-01', '2016-03-01', '2016-01-01', '2016-02-01', '2016-03-01', '2016-01-01', '2016-02-01', '2016-03-01', '2016-01-01', '2016-02-01', '2016-03-01'], 'cost': [43, 45, 46, 41, 48, 59, 8, 9, 10, 12, 15, 13] }
df = pd.DataFrame.from_dict(d)
df.set_index('prod_code', inplace=True)
for i, row in df.iterrows():
    print row.name, row['cost']

040201060AAAIAI 43
040201060AAAIAJ 45
040201060AAAIAI 46
040201060AAAIAI 41
040201060AAAIAI 48
040201060AAAIAI 59
040301060AAAKAG 8
040301060AAAKAK 9
040301060AAAKAK 10
040301060AAAKAX 12
040301060AAAKAK 15
040301060AAAKAK 13
</code></pre>

<p>you can learn more about it <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iterrows.html#pandas-dataframe-iterrows" rel="nofollow">here</a></p>

python pandas