<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def replace_nan( trainingset, replace_with = None ):
 # if replace_with = None, replaces with mean value """ Replace instanced of "not a number" with either the mean of the signal feature or a specific value assigned by `replace_nan_with` """

    training_data = np.array( [instance.features for instance in trainingset ] ).astype( np.float64 )
    
    def encoder( dataset ):
        for instance in dataset:
            instance.features = instance.features.astype( np.float64 )
            
            if np.sum(np.isnan( instance.features )):
                if replace_with == None:
                    instance.features[ np.isnan( instance.features ) ] = means[ np.isnan( instance.features ) ]
                else:
                    instance.features[ np.isnan( instance.features ) ] = replace_with
        return dataset
    #end
    
    if replace_nan_with == None:
        means = np.mean( np.nan_to_num(training_data), axis=0 )
    
    return encoder