pythonpandasdataframedata-processing

slicing all the columns of a dataframe simultaneously


I have a data frame of an ECG. The data frame consists of 12 columns (lead in ECG vocabulary). I want to cut some slices of all columns like the image below. I find the peak of the first column and define the length of the cut and slice all the columns simultaneously. Edit: In fact, I choose the highest peaks of the first column (lead) and stack them in a list named pos. Then, I use these peaks as my reference line and cut for ex 500 data points before and 500 data points after the reference line and stack them in the list named cut. This is my code but I get the error "list assignment index out of range"

def slicing (patient, pos, len):
   
   cut = []
   for lead in patient:
     for position in pos: 
        cut[position] = patient.loc[:, str(lead)][(position - len) : (position + len)]
        print (cut)

Could you please tell me how can I fix the error and how can I have my slices be named like cut[1] = [...] cut[2] = [...]


Solution

  • "list assignment index out of range" - this is because you are trying to assign a value to an index which is not present in the list. try append()

    Instead of just using for loop try enumerate() and rename() function for each slice

    Example:

    for i, lead in enumerate(patient.columns):
            for j, position in enumerate(pos):
    
                slice_name = f"cut{i+1}_{j+1}"
    
                cut.append(patient.loc[:, lead][(position - length) : (position + length)].rename(slice_name))
    return cut