python - 如何获取满足条件的多个列索引
问题描述
我有如下数据:
id attribute1 attribute2 attribute3 attribute4 attribute5 new otherattri
0 1 1 0 0 0 0 1 2
1 2 1 1 1 1 0 1234 12
2 3 0 0 0 0 1 5 21
3 4 1 0 1 0 0 13 93
4 5 0 0 0 1 0 4 2
名为的列new
是我要计算的。我应该怎么做才能在熊猫中实现这一目标?新列只是将数据框中的前 5 列组合成一个新列,例如对于第 4 行,attribute1 == 1 和 attribute3 == 1,因此 line4 的新列是 13。
提前致谢!
解决方案
df1=df.loc[:,df.columns[:-2]] #omitting the last 2 columns for reproducibility
df1['new']=df1.dot(df1.columns.str.replace('attribute',''))
print(df1)
attribute1 attribute2 attribute3 attribute4 attribute5 new
id
1 1 0 0 0 0 1
2 1 1 1 1 0 1234
3 0 0 0 0 1 5
4 1 0 1 0 0 13
5 0 0 0 1 0 4
推荐阅读
- django - ubuntu 20 上的 django apache2 设置用于内网访问
- python - pyenv:构建失败(Fedora 34 使用 python-build 20180424)
- javascript - PWA 启动画面和主屏幕上的图标出现在 iOS 设备中,但不在 Android 中(下面的 manifest.json 文件)
- algorithm - 在图像中找到非最大抑制的有效方法?
- python - 将 Dict 附加到 DataFrame 时,我得到“TypeError:'dict' object is not callable”
- python - 如何使用 Python 在现有 eml 文件中添加 pdf 附件?
- c++ - 用于使用 C++ 排序比较多个字段的 Lambda 表达式
- java - 无法启动 SAS 部署管理器 - java.library.path 中没有自由类型
- c - 在 C 结构数组中存储字符串时遇到问题
- mysql - 将 Blob 转换为 CSV - 日期格式