Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select non-zero columns in a matrix in python

Suppose I have data with following format:

C0 C1 C2 C3 C4 C5 C6 C7 C8
0  0  0  0  0  0  0  0  0
0  0  0  0  0  0  0  0  0
0  0  2  3  4  5  6  0  0
0  1  4  5  6  7  8  0  0
0  0  0  0  0  0  0  0  0

I want to select non-zero columns, such that column C1, C2, C3, C4, C5, C6 in python. Any command that can directly give me desired format.

like image 774
Rayyan Khan Avatar asked Jun 01 '26 19:06

Rayyan Khan


2 Answers

You can use any along with numpy indexing to select columns with non-zero values.

Setup

a = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 2, 3, 4, 5, 6, 0, 0],
              [0, 1, 4, 5, 6, 7, 8, 0, 0],
              [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=int64)

a[:, a.any(0)]

array([[0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 2, 3, 4, 5, 6],
       [1, 4, 5, 6, 7, 8],
       [0, 0, 0, 0, 0, 0]], dtype=int64)
like image 163
user3483203 Avatar answered Jun 04 '26 08:06

user3483203


If you use a library like pandas then it is way more simpler

You just take mean of each column and if they are greater than 0 they are your required columns

For that I will give you a piece of code:

import pandas as pd

df = pd.read_csv("File Path")
a = df.mean(axis=0) #gives you column wise mean
for i in len(a):
   if a[i] > 0:
      print(i)  # i will be your column
like image 41
Maheshwar Kuchana Avatar answered Jun 04 '26 08:06

Maheshwar Kuchana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!