python - 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
解决方案
让我们尝试一些不同的东西。我们可以将太阳穿过轴 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)
推荐阅读
- javascript - 以有效的方式处理和存储对象
- javascript - Discord.js 中的多个前缀
- python - 在 Tkinter 中将背景图像添加到新窗口
- flutter - Flutter:如何在 AppBar 中使用动画图标 - 我想在 Flutter 应用的 appbar 中使用这个动画图标而不是 Animatedless Icon
- python - 在 Python 中使用导入文件中的变量
- cognos - COGNOS 11 - 查询计算的手动输入列
- flutter - 断言失败:第 50 行 pos 15:'image != null':在 Flutter 中不正确
- c# - 将 int 转换为 List
, ChartJS 核心 - php - Laravel 页面中的动态文本字段
- postgresql - 查询关联表PK上的多:多关系(即按关联表列过滤)