我有一个数据框:
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指数行"而不是" pandas系列名称"。
答案 0 :(得分:7)
for i, row in df.iterrows():
为每个行Series
返回Series
,其中index
名称是您正在迭代的行的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
。你可以简单地做
import * as reduxFetchHelpers from 'redux-fetch-helpers';
您可以详细了解here
答案 1 :(得分:0)
使用它迭代任何值df.ix[row_value,col_value]
以查找列索引使用此函数
def find_column_number(column_name):
x=list(df1.columns.values)
print column_name
col_lenth= len(x)
counter=0
count=[]
while counter<col_lenth:
if x[counter]==column_name:
count=counter
counter+=1
return count