我有一个数据帧:
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
如何遍历行,并获取每个行的索引值?
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.index, row['cost']
但我明白了:
Index([u'items', u'cost'], dtype='object') 3.34461552621
更新:这与询问如何获取系列索引的名称相同,但措辞不同.虽然答案与另一个问题相同,但问题不一样!具体来说,这个问题将在人们谷歌搜索“pandas index of row”而不是“pandas name of series”时发现.
解决方法:
for i, row in df.iterrows():
为每行返回一个Series,其中Series name是您要迭代的行的索引.你可以干脆做
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
你可以了解更多关于它here
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。