claudiu-c
6/11/2018 - 2:41 PM

Pandas

pandas

table = df.to_html(
    columns=["gene_name", "gene_abundance", "log2_fold_change"],
    table_id="gene_abundance_table",
    justify="left",
    index=False
)

return table

def get_hex_color_indexes(
    values: "np.ndarray[float]", colors: List[str]
) -> "np.ndarray[int]":
    """
    This has as an input a list of numbers and a list of colors and calculates to which color do the values correspond.

    Args:
        values: an array of values that we want to associate colors with.
        colors: the colors that we want to associate with the values.

    Returns:
        An array like this [7, 4, 6] which represents the index of the colors.
    """
    if values.max() - values.min() == 0:
        return np.array([0])

    else:
        hex_colors = (
            (values - values.min()) / (values.max() - values.min()) * (len(colors) - 1)
        ).astype(np.int16)

        return hex_colors


def add_colors_to_df(
    df: pd.DataFrame, colors: Dict[str, "np.ndarray[str]"], column: str
) -> pd.DataFrame:
    """
    Add colors to the dataframe on each row.
        anything between -2 and 2 is neutral because we're not interested in it
        below -2 is dark blue
        above 2 is red/dark red
    Args:
        df: Dataframe without colors
        colors("np.ndarray[str]"): The list of colors, from blue to red
        column(str): the column by which we calculate the colors
    Returns:
         pd.DataFrame: Dataframe with colors in column hex_color
    """
    df["hex_color"] = ""
    df[column] = df[column].fillna(value=0)
    df[column] = replace_empty_strings_with_nan(df[[column]])[column]
    color_values = df[column].values.copy()
    color_values[pd.isnull(color_values)] = 0
    blue = color_values[color_values < -2]
    red = color_values[color_values > 2]
    color_normal_background = "#f5f5dc"

    if blue.size > 0:
        hex_colors_dark_blue = get_hex_color_indexes(blue, colors["blue"])
        df.loc[df[column] < -2, "hex_color"] = colors["blue"][hex_colors_dark_blue]

    if red.size > 0:
        hex_colors_red = get_hex_color_indexes(red, colors["red"])
        df.loc[df[column] > 2, "hex_color"] = colors["red"][hex_colors_red]

    df.loc[
        (
            pd.isnull(df[column]) | df[column]
            == 0
            | ((df[column] > 0) & (df[column] <= 2))
            | ((df[column] < 0) & (df[column] >= -2))
        ),
        "hex_color",
    ] = color_normal_background  # we're not interested if it's between -2 and 2

    return df