Python 如何根据存在值的it列名创建新的dataframe?

Python 如何根据存在值的it列名创建新的dataframe?,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个数据框: Index 0 1 2 0 0 1 0 1 0 0 1 2 1 0 0 3 0 0 1 如何根据存在值的it列名或当值=1时创建新的dataframe 预期产出: Index type 0 1 1 2 2 0 3 2 如果列中只有1或0个值,则使用: #if Index is not column, bu

我有一个数据框:

 Index   0   1   2
     0   0   1   0
     1   0   0   1
     2   1   0   0
     3   0   0   1
如何根据存在值的it列名或当值=1时创建新的dataframe

预期产出:

 Index   type
     0    1
     1    2
     2    0
     3    2
如果列中只有1或0个值,则使用:

#if Index is not column, but index
df['type'] = df.dot(df.columns)
#if Index is column or necessary omit first column
#df['type'] = df.iloc[:, 1:].dot(df.columns[1:])
print (df)
       0  1  2 type
Index              
0      0  1  0    1
1      0  0  1    2
2      1  0  0    0
3      0  0  1    2
如果每行没有1个值,则解决方案也正常工作,然后返回空字符串:

df['type'] = df.dot(df.columns)
print (df)
       0  1  2 type
Index              
0      0  0  0     
1      0  0  1    2
2      1  0  0    0
3      0  0  1    2
如果列中只有1或0个值,则使用:

#if Index is not column, but index
df['type'] = df.dot(df.columns)
#if Index is column or necessary omit first column
#df['type'] = df.iloc[:, 1:].dot(df.columns[1:])
print (df)
       0  1  2 type
Index              
0      0  1  0    1
1      0  0  1    2
2      1  0  0    0
3      0  0  1    2
如果每行没有1个值,则解决方案也正常工作,然后返回空字符串:

df['type'] = df.dot(df.columns)
print (df)
       0  1  2 type
Index              
0      0  0  0     
1      0  0  1    2
2      1  0  0    0
3      0  0  1    2
这里有一种使用

这里有一种使用


因为它看起来像傻瓜。你也可以使用

>>>df['type']=df.idxmaxaxaxis=1 >>>df 0 1 2类型 0 0 1 0 1 1 0 0 1 2 2 1 0 0 0 3 0 0 1 2
因为它看起来像傻瓜。你也可以使用

>>>df['type']=df.idxmaxaxaxis=1 >>>df 0 1 2类型 0 0 1 0 1 1 0 0 1 2 2 1 0 0 0 3 0 0 1 2