Python Correlation Matrix: Calculate Correlations Between Lists
To compute the correlation matrix of several lists in Python, you can use the 'numpy' library. Here's an example:
import numpy as np
# Define the lists
list1 = [1, 2, 3, 4, 5]
list2 = [5, 4, 3, 2, 1]
list3 = [2, 4, 6, 8, 10]
# Create a 2D array to hold the lists
data = np.array([list1, list2, list3])
# Compute the correlation matrix
correlation_matrix = np.corrcoef(data)
# Print the correlation matrix
print(correlation_matrix)
In this example, we have three lists: 'list1', 'list2', and 'list3'. You can replace these with your own lists.
We create a 2D array 'data' using 'numpy.array()' to hold the lists. Each list represents a row in the array.
Next, we compute the correlation matrix using 'np.corrcoef()', which calculates the correlation coefficients between the rows of the 'data' array.
Finally, we print the correlation matrix using 'print(correlation_matrix)'.
The resulting correlation matrix will be a square matrix where each element represents the correlation coefficient between two lists. The diagonal elements will be 1 since it represents the correlation of each list with itself.
原文地址: https://www.cveoy.top/t/topic/tzg 著作权归作者所有。请勿转载和采集!