1

I got a matrix of the form:

      1.0  2.0  3.0  4.0
1      0    0    0    1
2      0    0    1    0
3      1    0    0    0
4      0    1    0    0
5      1    0    0    0
6      0    0    0    0
7      1    0    0    0

I want to add another column in the matrix where its value will be 1 only if every other value is 0 and 0 otherwise. So visually i want this:

      1.0  2.0  3.0  4.0  5.0
1      0    0    0    1   0
2      0    0    1    0   0
3      1    0    0    0   0
4      0    1    0    0   0
5      1    0    0    0   0
6      0    0    0    0   1
7      1    0    0    0   0
Alkis Ko
  • 99
  • 1
  • 12

4 Answers4

2

Lets try something different. we can take sun acriss axis 1 and convert to np.sign then subtract that result with 1 which converts 0 to 1 and 1 to 0.

df['5.0'] = 1-np.sign(df.sum(1))

Or with df.any(axis=1)

df['5.0'] = 1-df.any(1)

print(df)

   1.0  2.0  3.0  4.0  5.0
1    0    0    0    1    0
2    0    0    1    0    0
3    1    0    0    0    0
4    0    1    0    0    0
5    1    0    0    0    0
6    0    0    0    0    1
7    1    0    0    0    0

If the a row can have just one 1 or less just do;

df['5.0'] = 1-df.sum(1)
anky
  • 74,114
  • 11
  • 41
  • 70
1

this must do the job :

df['05']=(df.sum(axis=1)==0).astype(int)
gilf0yle
  • 1,092
  • 3
  • 9
0

Use df.apply to create a new series then assign like this:

df[5.0] = df.apply(lambda row: 1 if all(i == 0 for i in row) else 0, axis=1)
Abdul Aziz Barkat
  • 19,475
  • 3
  • 20
  • 33
0

You can convert the matrix to Dataframe function:

 matrixA = {}
 matrixA['1'] = [0, 0, 0, 1]
 matrixA['2'] = [0, 1, 0, 0]
 matrixA['3'] = [0, 0, 1, 1]
 matrixA['4'] = [0, 1, 1, 1]
 df = pd.DataFrame(matrixA)

after that add a lambda function

df['5'] = df.apply(lambda x: 
     get_sum_of_1(list(x)),axis=1).reset_index(drop=True).copy()

and the calculated row function will be:

def get_sum_of_1(row):
    return row.count(1) % 2
shaked
  • 11
  • 1
  • 1