def correlation ( df , rowvar = False ) : # Create a correlation matrix for all correlations # of the columns (filled with na for all values) df = df . copy ( ) maskv = np . ma . masked_where ( np . isnan ( df . values ) , df . values ) cdf = np . ma . corrcoef ( maskv , rowvar = False ) cdf = pd . DataFrame ( np . array ( cdf ) ) cdf . columns = df . columns cdf . index = df . columns cdf = cdf . sort_index ( level = 0 , axis = 1 ) cdf = cdf . sort_index ( level = 0 ) return cdf
python correlation function on specific columns
Calculate column - wise Pearson correlations using numpy . ma . corrcoef
def correlation(df, rowvar=False):
    """
    Calculate column-wise Pearson correlations using ``numpy.ma.corrcoef``

    Input data is masked to ignore NaNs when calculating correlations. Data is returned as
    a Pandas ``DataFrame`` of column_n x column_n dimensions, with column index copied to
    both axes.

    :param df: Pandas DataFrame
    :return: Pandas DataFrame (n_columns x n_columns) of column-wise correlations
    """

    # Create a correlation matrix for all correlations
    # of the columns (filled with na for all values)
    df = df.copy()
    maskv = np.ma.masked_where(np.isnan(df.values), df.values)
    cdf = np.ma.corrcoef(maskv, rowvar=False)
    cdf = pd.DataFrame(np.array(cdf))
    cdf.columns = df.columns
    cdf.index = df.columns
    cdf = cdf.sort_index(level=0, axis=1)
    cdf = cdf.sort_index(level=0)
    return cdf