创建值= 1的记录的子集。忽略其他值,因为它们不携带任何信息

时间:2019-01-18 19:52:14

标签: python python-3.x pandas

我有以下数据框:

enter image description here

我需要通过忽略0值来创建另一个数据框。例如,在第三行中,第一列的值是3D,为此,实际值是Manufacturing,因为其中有1。相同的规则适用于所有行。最后,我需要在结果数据帧中的两列,其中包含categroy_list及其值。

正在查看pandas doc,也许可以通过melt()完成,但我无法做到这一点。请帮忙。

1 个答案:

答案 0 :(得分:0)

如果我了解您在寻找什么...

从(index,col)对创建数据框后,您可以使用update

# sample data
df = pd.DataFrame({'cat_list':list('ABCDE'),
                   'col2':[0]*5,
                   'col2':[0,0,1,0,1],
                   'col3':[1,1,0,0,0],
                   'col4':[0,0,0,1,0]})

# index,col values where df==1
new = pd.DataFrame(list(df[df ==1 ].stack().index)).set_index(0).rename(columns={1:'cat_list'})
df.update(new)

  cat_list  col2  col3  col4
0     col3     0     1     0
1     col3     0     1     0
2     col2     1     0     0
3     col4     0     0     1
4     col2     1     0     0

还是您要合并?

# sample data
df = pd.DataFrame({'cat_list':list('ABCDE'),
                   'col2':[0]*5,
                   'col2':[0,0,1,0,1],
                   'col3':[1,1,0,0,0],
                   'col4':[0,0,0,1,0]})

# index,col values where df==1
new = pd.DataFrame(list(df[df ==1 ].stack().index)).set_index(0).rename(columns={1:'cat_list'})
df.merge(new, left_index=True, right_index=True)

  cat_list_x  col2  col3  col4 cat_list_y
0          A     0     1     0       col3
1          B     0     1     0       col3
2          C     1     0     0       col2
3          D     0     0     1       col4
4          E     1     0     0       col2