首页 > 解决方案 > 如何获取满足条件的多个列索引

问题描述

我有如下数据:

   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。
提前致谢!

标签: pythonpython-3.xpandasnumpy

解决方案


.dot()

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

推荐阅读