In addition to all the excellent previous answers above, here is a solution to this problem when working with pandas Series objects. In many cases, pandas Series have custom/unique indices (for example, unique identifier strings) that can't be accessed with the enumerate() function.
xs = pd.Series([8, 23, 45]) xs.index = ['G923002', 'G923004', 'G923005'] print(xs)Output:
# G923002 8 # G923004 23 # G923005 45 # dtype: int64
xs = pd.Series([8, 23, 45])
xs.index = ['G923002', 'G923004', 'G923005']
print(xs)
Output:
# G923002 8
# G923004 23
# G923005 45
# dtype: int64
We can see below that enumerate() doesn't give us the desired result:
for id, x in enumerate(xs): print("id #{} = {}".format(id, x))Output:
# id #0 = 8 # id #1 = 23 # id #2 = 45
for id, x in enumerate(xs):
print("id #{} = {}".format(id, x))
Output:
# id #0 = 8
# id #1 = 23
# id #2 = 45
We can access the indices of a pandas Series in a for loop using .items():
for id, x in xs.items(): print("id #{} = {}".format(id, x))Output:
# id #G923002 = 8 # id #G923004 = 23 # id #G923005 = 45
for id, x in xs.items():
print("id #{} = {}".format(id, x))
Output:
# id #G923002 = 8
# id #G923004 = 23
# id #G923005 = 45