def to_df(
        self,
        rank="auto",
        top_n=None,
        threshold=None,
        remove_zeros=True,
        normalize="auto",
        table_format="wide",
    ):
        """Takes the ClassificationsDataFrame associated with these samples, or SampleCollection,
        does some filtering, and returns a ClassificationsDataFrame copy.

        Parameters
        ----------
        rank : {'auto', 'kingdom', 'phylum', 'class', 'order', 'family', 'genus', 'species'}, optional
            Analysis will be restricted to abundances of taxa at the specified level.
        top_n : `integer`, optional
            Return only the top N most abundant taxa.
        threshold : `float`, optional
            Return only taxa more abundant than this threshold in one or more samples.
        remove_zeros : `bool`, optional
            Do not return taxa that have zero abundance in every sample.
        normalize : {'auto', True, False}
            Convert read counts to relative abundances (each sample sums to 1.0).
        table_format : {'long', 'wide'}
            If wide, rows are classifications, cols are taxa, elements are counts. If long, rows are
            observations with three cols each: classification_id, tax_id, and count.

        Returns
        -------
        `ClassificationsDataFrame`
        """
        from onecodex.dataframes import ClassificationsDataFrame

        rank = self._get_auto_rank(rank)
        df = self._results.copy()

        # subset by taxa
        if rank:
            if rank == "kingdom":
                warnings.warn(
                    "Did you mean to specify rank=kingdom? Use rank=superkingdom to see Bacteria, "
                    "Archaea and Eukaryota."
                )

            tax_ids_to_keep = []

            for tax_id in df.keys():
                if self.taxonomy["rank"][tax_id] == rank:
                    tax_ids_to_keep.append(tax_id)

            if len(tax_ids_to_keep) == 0:
                raise OneCodexException("No taxa kept--is rank ({}) correct?".format(rank))

            df = df.loc[:, tax_ids_to_keep]

        # normalize
        if normalize is False and self._guess_normalized():
            raise OneCodexException("Data has already been normalized and this can not be undone.")

        if normalize is True or (
            normalize == "auto" and rank is not None and self._field != "abundance"
        ):
            df = df.div(df.sum(axis=1), axis=0)

        # remove columns (tax_ids) with no values that are > 0
        if remove_zeros:
            df = df.loc[:, (df != 0).any(axis=0)]

        # restrict to taxa appearing in one or more samples at the given threshold
        if threshold:
            df = df.loc[:, df.max() >= threshold]

        # restrict to N most abundant taxa
        if top_n:
            idx = df.sum(axis=0).sort_values(ascending=False).head(top_n).index
            df = df.loc[:, idx]

        # additional data to copy into the ClassificationsDataFrame
        ocx_data = {
            "ocx_metadata": self.metadata.copy(),
            "ocx_rank": rank,
            "ocx_field": self._field,
            "ocx_taxonomy": self.taxonomy.copy(),
            "ocx_normalized": normalize,
        }

        # generate long-format table
        if table_format == "long":
            long_df = {"classification_id": [], "tax_id": [], self._field: []}

            for t_id in df:
                for c_id, count in df[t_id].iteritems():
                    long_df["classification_id"].append(c_id)
                    long_df["tax_id"].append(t_id)
                    long_df[self._field].append(count)

            results_df = ClassificationsDataFrame(long_df, **ocx_data)
        elif table_format == "wide":
            results_df = ClassificationsDataFrame(df, **ocx_data)
        else:
            raise OneCodexException("table_format must be one of: long, wide")

        return results_df
def to_df ( self , rank = "auto" , top_n = None , threshold = None , remove_zeros = True , normalize = "auto" , table_format = "wide" , ) : from onecodex . dataframes import ClassificationsDataFrame rank = self . _get_auto_rank ( rank ) df = self . _results . copy ( ) if rank : if rank == "kingdom" : warnings . warn ( "Did you mean to specify rank=kingdom? Use rank=superkingdom to see Bacteria, " "Archaea and Eukaryota." ) tax_ids_to_keep = [ ] for tax_id in df . keys ( ) : if self . taxonomy [ "rank" ] [ tax_id ] == rank : tax_ids_to_keep . append ( tax_id ) if len ( tax_ids_to_keep ) == 0 : raise OneCodexException ( "No taxa kept--is rank ({}) correct?" . format ( rank ) ) df = df . loc [ : , tax_ids_to_keep ] if normalize is False and self . _guess_normalized ( ) : raise OneCodexException ( "Data has already been normalized and this can not be undone." ) if normalize is True or ( normalize == "auto" and rank is not None and self . _field != "abundance" ) : df = df . div ( df . sum ( axis = 1 ) , axis = 0 ) if remove_zeros : df = df . loc [ : , ( df != 0 ) . any ( axis = 0 ) ] if threshold : df = df . loc [ : , df . max ( ) >= threshold ] if top_n : idx = df . sum ( axis = 0 ) . sort_values ( ascending = False ) . head ( top_n ) . index df = df . loc [ : , idx ] ocx_data = { "ocx_metadata" : self . metadata . copy ( ) , "ocx_rank" : rank , "ocx_field" : self . _field , "ocx_taxonomy" : self . taxonomy . copy ( ) , "ocx_normalized" : normalize , } if table_format == "long" : long_df = { "classification_id" : [ ] , "tax_id" : [ ] , self . _field : [ ] } for t_id in df : for c_id , count in df [ t_id ] . iteritems ( ) : long_df [ "classification_id" ] . append ( c_id ) long_df [ "tax_id" ] . append ( t_id ) long_df [ self . _field ] . append ( count ) results_df = ClassificationsDataFrame ( long_df , ** ocx_data ) elif table_format == "wide" : results_df = ClassificationsDataFrame ( df , ** ocx_data ) else : raise OneCodexException ( "table_format must be one of: long, wide" ) return results_df
Takes the ClassificationsDataFrame associated with these samples, or SampleCollection,
        does some filtering, and returns a ClassificationsDataFrame copy.

        Parameters
        ----------
        rank : {'auto', 'kingdom', 'phylum', 'class', 'order', 'family', 'genus', 'species'}, optional
            Analysis will be restricted to abundances of taxa at the specified level.
        top_n : `integer`, optional
            Return only the top N most abundant taxa.
        threshold : `float`, optional
            Return only taxa more abundant than this threshold in one or more samples.
        remove_zeros : `bool`, optional
            Do not return taxa that have zero abundance in every sample.
        normalize : {'auto', True, False}
            Convert read counts to relative abundances (each sample sums to 1.0).
        table_format : {'long', 'wide'}
            If wide, rows are classifications, cols are taxa, elements are counts. If long, rows are
            observations with three cols each: classification_id, tax_id, and count.

        Returns
        -------
        `ClassificationsDataFrame`