![]() |
How to only extract upper or lower triangular matrix into tabular form - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to only extract upper or lower triangular matrix into tabular form (/thread-15071.html) |
How to only extract upper or lower triangular matrix into tabular form - SriRajesh - Jan-02-2019 Hi, I have correlation matrix as below my raw data is stored in variable "x" x: A B C D 1.2 2.3 5.6 1.0 1.3 5.6 2.3 2.9 5.6 0.7 3.9 2.8 1.3 1.9 2.8 0.8 3.3 0.9 2.8 1.3 4.3 0.6 1.3 2.8 7.3 2.8 0.05 2.8 2.3 2.8 1.03 0.6 import seaborn as sns f,ax=plt.subplots(figsize=(10,10)) corr=x.corr() sns.heatmap(corr,mask=np.zeros_like(corr,dtype=np.bool),cmap=sns.diverging_palette(220,10,as_cmap=True),square=True,ax,ax) a=x.corr() b=x.corr() corrFilter=x.corr() s=corrFilter.unstack() so=s.sort_values(kind="quicksort")I want to remove diagonal, and only extract upper or lower triangular matrix. I use the below code, but it still retain for example B-->A (But it same as A-->B). How to remove duplicate in reverse order(meaning, just retain A-->B, and omit B-->A) RE: How to only extract upper or lower triangular matrix into tabular form - scidam - Jan-03-2019 Is x assumed to be a data frame (pandas)?If you want to extract upper/lower triangle of a matrix, you can use numpy.triu and numpy.tril utility functions, e.g.:import pandas as pd # a piece of code where x becomes defined pd.np.triu(x.corr().values) pd.np.tril(x.corr().values) RE: How to only extract upper or lower triangular matrix into tabular form - SriRajesh - Jan-03-2019 x is my input data, and after correlation matrix, want to extract upper or lower triangle matrix into tabular form. Here 4 variable, I want to upper (or lower triangle) matrix: Column1 Column2 Corr.coeficient A B 0.4 A C 0.8 A D 0.5 B C 0.5 B D 0.8 C D 0.6 RE: How to only extract upper or lower triangular matrix into tabular form - scidam - Jan-04-2019 x.corr().where(pd.np.triu(pd.np.ones(x.shape), k=1).astype(bool)).stack().reset_index()You can change k to 0 to include the main diagonal of the correlation matrix.
|