Home > front end >  Iterate over a dataframe after set index
Iterate over a dataframe after set index

Time:12-15

I have a dataframe and a want to make his index start from 1 instead of 0. I can do it with no problems like the example below

data = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']}
df = pd.DataFrame.from_dict(data)
df.index  = 1

but, when I try to iterate over the rows it raises the error "single positional indexer is out-of-bounds" when the last index is reached, see:

for index, line in df.iterrows():
  print(df.loc[index])

How can I iterate over the dataframe even when I reindex him?

CodePudding user response:

data = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']}

df = pd.DataFrame.from_dict(data, index=range(1, len(data) 1))

df.index = 1

or

data = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']} df = pd.DataFrame.from_dict(data)

DataFrame df.index = range(1, len(df) 1)

df.index = 1

CodePudding user response:

Using df.loc[index] instead df.iloc[index] solved the problem. Seems that iloc[] keeps indexing from zero, independently of the dataframe index.

  • Related