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
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)
this must do the job:
df['05']=(df.sum(axis=1)==0).astype(int)
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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.