【问题标题】:Heatmap plot of a pandas dataframe - TypeError熊猫数据框的热图 - TypeError
【发布时间】:2019-01-18 06:42:04
【问题描述】:

我有两个经过检查看起来相同的 pandas 数据框。一个是使用 Pandas 内置创建的:

df.corr(method='pearson')

而另一个是使用自定义函数创建的:

def cor_matrix(dataframe, method):
    coeffmat = pd.DataFrame(index=dataframe.columns, 
columns=dataframe.columns)
    pvalmat = pd.DataFrame(index=dataframe.columns, columns=dataframe.columns)
    for i in range(dataframe.shape[1]):
        for j in range(dataframe.shape[1]):
            x = np.array(dataframe[dataframe.columns[i]])
            y = np.array(dataframe[dataframe.columns[j]])
            bad = ~np.logical_or(np.isnan(x), np.isnan(y))
            if method == 'spearman':
                corrtest = spearmanr(np.compress(bad,x), np.compress(bad,y))
            if method == 'pearson':
                corrtest = pearsonr(np.compress(bad,x), np.compress(bad,y))
            coeffmat.iloc[i,j] = corrtest[0]
            pvalmat.iloc[i,j] = corrtest[1]
    return (coeffmat, pvalmat)

两者看起来相同并且具有相同的类型(pandas.core.frame.DataFrame)并且它们的条目也具有相同的类型(numpy.float64)

但是,当我尝试使用以下方法绘制这些内容时:

import matplotlib.pyplot as plt
plt.imshow((df))

只有使用 pandas 内置函数创建的数据框才有效。对于其他数据框,我收到错误:TypeError:图像数据无法转换为浮点数。谁能解释发生了什么,这两个数据帧有何不同以及如何解决该错误?

编辑 - 看起来好像有一个区别,当我将数据帧转换为 numpy 数组时,不起作用的那个最后有 dtype = object。有没有办法去掉这个?

【问题讨论】:

  • 你可能总是绘制 numpy 数组,imshow(df.values.astype(np.float64))

标签: python pandas matplotlib typeerror


【解决方案1】:

修改函数以将数据框指定为浮点数修复了问题:

def cor_matrix(dataframe, method):
    coeffmat = pd.DataFrame(index=dataframe.columns, columns=dataframe.columns)
    pvalmat = pd.DataFrame(index=dataframe.columns, columns=dataframe.columns)
    for i in range(dataframe.shape[1]):
        for j in range(dataframe.shape[1]):
            x = np.array(dataframe[dataframe.columns[i]])
            y = np.array(dataframe[dataframe.columns[j]])
            bad = ~np.logical_or(np.isnan(x), np.isnan(y))
            if method == 'spearman':
                corrtest = spearmanr(np.compress(bad,x), np.compress(bad,y))
            if method == 'pearson':
                corrtest = pearsonr(np.compress(bad,x), np.compress(bad,y))
            coeffmat.iloc[i,j] = corrtest[0]
            pvalmat.iloc[i,j] = corrtest[1]
    #This is to convert to float type otherwise can cause problems when e.g. plotting
    coeffmat=coeffmat.apply(pd.to_numeric, errors='ignore')
    pvalmat=pvalmat.apply(pd.to_numeric, errors='ignore')
    return (coeffmat, pvalmat)

【讨论】:

    猜你喜欢
    • 2017-09-05
    • 2021-09-26
    • 1970-01-01
    • 2015-07-08
    • 2016-08-03
    • 1970-01-01
    • 2013-08-16
    • 2022-01-15
    相关资源
    最近更新 更多