Home > other >  "Keyerror" - Iterating through each element in Dataframe
"Keyerror" - Iterating through each element in Dataframe

Time:04-06

Trying to iterate through each element in a 2D Dataframe so that if the value for a column has changed from previous row to 1, that value would be left intact, but otherwise the value would always become 0.

Tried the code below, however I get a "Keyerror:0" or "Keyerror:1" depending on what I define as range start. Any ideas to fix it or do it in another way?

for R in range(1, signal_data.shape[0]):
      for C in range(1, signal_data.shape[1]):
                    if signal_data[C][R] - signal_data[C][R-1] == 1:
                          signal_data[C][R] = 1
                    else:
                            signal_data[C][R] = 0

CodePudding user response:

You can not call a pandas dataframe column by its id like that. Either use the real column name (you can get them using df.columns and store it in a list) or use loc

Seeing your code, you may consider using a numpy.array instead of a pandas.DataFrame

  • Related