pandas: get the value of the index for a row?
for idx, row in df.iterrows():
returns a Series
for each row where idx
is the index
of the row you are iterating through. you could simply do
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 idx, row in df.iterrows():
print(idx, 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
you can learn more about it here