def acollapse (a,keepcols,collapsecols,fcn1=None,fcn2=None,cfcn=None):
        """
    Averages data in collapsecol, keeping all unique items in keepcols
    (using unique, which keeps unique LISTS of column numbers), retaining
    the unique sets of values in keepcols, the mean for each.  If stderror or
    N of the mean are desired, set either or both parameters to 1.
    
    Usage:   acollapse (a,keepcols,collapsecols,fcn1=None,fcn2=None,cfcn=None)
    Returns: unique 'conditions' specified by the contents of columns specified
             by keepcols, abutted with the mean(s) of column(s) specified by
             collapsecols
    """
        def acollmean (inarray):
            return N.sum(N.ravel(inarray))
    
        if type(keepcols) not in [ListType,TupleType,N.ndarray]:
            keepcols = [keepcols]
        if type(collapsecols) not in [ListType,TupleType,N.ndarray]:
            collapsecols = [collapsecols]
    
        if cfcn == None:
            cfcn = acollmean
        if keepcols == []:
            avgcol = acolex(a,collapsecols)
            means = N.sum(avgcol)/float(len(avgcol))
            if fcn1<>None:
                try:
                    test = fcn1(avgcol)
                except:
                    test = N.array(['N/A']*len(means))
                means = aabut(means,test)
            if fcn2<>None:
                try:
                    test = fcn2(avgcol)
                except:
                    test = N.array(['N/A']*len(means))
                means = aabut(means,test)
            return means
        else:
            if type(keepcols) not in [ListType,TupleType,N.ndarray]:
                keepcols = [keepcols]
            values = colex(a,keepcols)   # so that "item" can be appended (below)
            uniques = unique(values)  # get a LIST, so .sort keeps rows intact
            uniques.sort()
            newlist = []
            for item in uniques:
                if type(item) not in [ListType,TupleType,N.ndarray]:
                    item =[item]
                tmprows = alinexand(a,keepcols,item)
                for col in collapsecols:
                    avgcol = acolex(tmprows,col)
                    item.append(acollmean(avgcol))
                    if fcn1<>None:
                        try:
                            test = fcn1(avgcol)
                        except:
                            test = 'N/A'
                        item.append(test)
                    if fcn2<>None:
                        try:
                            test = fcn2(avgcol)
                        except:
                            test = 'N/A'
                        item.append(test)
                    newlist.append(item)
            try:
                new_a = N.array(newlist)
            except __HOLE__:
                new_a = N.array(newlist,'O')
            return new_a
dataset/ETHPy150Open sunlightlabs/clearspending/completeness/statlib/pstat.py/acollapse