Search code examples
pythoncorrelationpyqt6

How can I solve the error "TypeError: can only concatenate str (not "numpy.float64") to str" trying to output the correlation


I'm starting in Python and I'm trying to output in a QPlainTextEdit the Pearson's, Spearman's and Kendall's correlation using the function "print_correlation_results". But when I try to do it, I get this error, how can I solve it?

CORRELATION

def correlation_files(self):
    ...       
    
    if widgets.optLoadFiles.isChecked():
        ...
        if not result_file.error:
            if len(parameters_list)==2:
                ...
                
                widgets.txtParametersResult.setPlainText(widgets.txtParametersResult.toPlainText()+"\n"+self.print_correlation_results())        #Here I call the function
                
            ...
        
    
def print_correlation_results(self):
    
    parameters = widgets.cmbParametersFile.currentText()
    parameters_list = parameters.split(", ")
    FileName = widgets.txtDataFile.text()
    result_file = ResultFile(FileName)
    if not result_file.error:
        if len(parameters_list)==2:
            measurements = result_file.get_params(parameters_list)
            data1 = measurements[parameters_list[0]]["measure"]
            data2 = measurements[parameters_list[1]]["measure"]
    
    # calculate correlation
    corr, pvalue = pearsonr(data1, data2) # Pearson's r, valor p
    corr2, pvalue2 = spearmanr(data1, data2) # Spearman's rho, valor p
    corr3, pvalue3 = kendalltau(data1, data2) # Kendall's tau, valor p
    
    print_correlation_results =" - Pearsons correlation:\t " + corr + pvalue + "\n"
    print_correlation_results +=" - Spearmanr correlation:\t" + corr2 + pvalue2 + "\n"
    print_correlation_results +=" - kendalltau correlation:\t" + corr3 + pvalue3 + "\n"

Solution

  • Exactly what the error says. First of all you need to tell us in what line it found the error, because I'm gonna make a guess right now. I think the line was this one:

     print_correlation_results =" - Pearsons correlation:\t " + corr + pvalue + "\n"
    

    It's as if you'd be saying:

    "asdf" + 5
    

    You can't do that. In this case it's a numpy float, not an integer. But it's the same thing. corr, pvalue or both of them isnt a string. So you need to make them a string before you concatenate it with " - Pearsons correlation:\t "