Python为矩阵的下三角生成掩码

时间:2018-12-17 19:58:20

标签: python numpy matrix seaborn

我从seaborn文档中获得了这段代码,用于为给定相关矩阵的上三角生成掩码

# Compute the correlation matrix
corr = d.corr()

# Generate a mask for the upper triangle

mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True

如何实现倒置,即下三角形的遮罩?

3 个答案:

答案 0 :(得分:4)

只需将def cpc_hierarchy(cpc_series): pat1 = '(.)(\d{2})(.)(\d{2,3})' pat2 = '(\d{2}\/\d{1})' pat3 = '(\d{2}\/\d{2})' expanded = (pd.concat([ cpc_series.to_frame(), cpc_series.str.extract(pat1), cpc_series.str.extract(pat2), cpc_series.str.extract(pat3)], ignore_index=True, axis=1).set_index(0).rename_axis('CPC', 0)) return expanded print(cpc_hierarchy(df['CPC'])) 1 2 3 4 5 6 CPC Y10T403/4602 Y 10 T 403 03/4 03/46 H02S20/00 H 02 S 20 20/0 20/00 H01L31/02168 H 01 L 31 31/0 31/02 替换为public class MainActivity extends AppCompatActivity { LinearLayout mainLayout; ScrollView scrollView; LinearLayout fileSelector; EditText name; EditText password; Button submit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mainLayout = new LinearLayout(this); mainLayout.setOrientation(LinearLayout.VERTICAL); fileSelector = new LinearLayout(this); fileSelector.setOrientation(LinearLayout.VERTICAL); scrollView = new ScrollView(this); scrollView.addView(fileSelector); mainLayout.addView(scrollView); name = new EditText(this); password = new EditText(this); submit = new Button(this); submit.setText("Login"); for(int i=0; i<100; i++) { Button b = new Button(this); b.setText("hello"); fileSelector.addView(b); } mainLayout.addView(name); mainLayout.addView(password); mainLayout.addView(submit); setContentView(mainLayout); } public void onClick(View v) { } }

triu_indices_from

答案 1 :(得分:1)

对矩阵进行转置:

mask = mask.T

mask
array([[ True, False, False, False, False],
       [ True,  True, False, False, False],
       [ True,  True,  True, False, False],
       [ True,  True,  True,  True, False],
       [ True,  True,  True,  True,  True]])

mask.T
array([[ True, False, False, False, False],
       [ True,  True, False, False, False],
       [ True,  True,  True, False, False],
       [ True,  True,  True,  True, False],
       [ True,  True,  True,  True,  True]])

不过,这更多是一种解决方法,正确的解决方案是@john的

答案 2 :(得分:0)

您可以简单地转置具有的蒙版:

mask = np.zeros_like(corr, dtype=np.bool).T
mask[np.triu_indices_from(mask)] = True