Чтобы найти пары с наивысшей корреляцией в DataFrame pandas, вы можете использовать разные методы. Вот несколько подходов с примерами кода:
-
Использование метода
corr:import pandas as pd # Create a DataFrame df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [2, 4, 6, 8, 10], 'C': [5, 10, 15, 20, 25], 'D': [1, 3, 5, 7, 9]}) # Compute the correlation matrix corr_matrix = df.corr() # Find the highest correlation pairs highest_corr_pairs = corr_matrix.unstack().sort_values(ascending=False).drop_duplicates() print(highest_corr_pairs) -
Использование метода
corrwith:import pandas as pd # Create a DataFrame df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [2, 4, 6, 8, 10], 'C': [5, 10, 15, 20, 25], 'D': [1, 3, 5, 7, 9]}) # Compute the correlation with other columns corr_with_columns = df.corrwith(df) # Find the highest correlation pairs highest_corr_pairs = corr_with_columns.sort_values(ascending=False) print(highest_corr_pairs) -
Использование функции
numpy.corrcoef:import pandas as pd import numpy as np # Create a DataFrame df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [2, 4, 6, 8, 10], 'C': [5, 10, 15, 20, 25], 'D': [1, 3, 5, 7, 9]}) # Compute the correlation matrix using numpy corr_matrix = np.corrcoef(df.T) # Find the highest correlation pairs n = len(df.columns) highest_corr_pairs = [] for i in range(n): for j in range(i + 1, n): corr = corr_matrix[i, j] highest_corr_pairs.append((df.columns[i], df.columns[j], corr)) highest_corr_pairs.sort(key=lambda x: abs(x[2]), reverse=True) print(highest_corr_pairs)
Эти методы дадут вам пары с самой высокой корреляцией в вашем DataFrame. Вы можете выбрать тот, который лучше всего соответствует вашим потребностям.