首页 > 解决方案 > Add a column according to other columns in a matrix. [python]

问题描述

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

标签: pythonpandasdataframematrixmultiple-columns

解决方案


让我们尝试一些不同的东西。我们可以将太阳穿过轴 1 并转换为np.sign然后用 1 减去该结果,将 0 转换为 1 并将 1 转换为 0。

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

或与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

如果一行只能有一个 1 或更少就行;

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

推荐阅读