Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 选择列中值为1的列名_Python_Pandas - Fatal编程技术网

Python 选择列中值为1的列名

Python 选择列中值为1的列名,python,pandas,Python,Pandas,我有这个数据框: Course_2013 AP Advanced Vocational Basic ESL 0 7th Math Enrich 0 1 0 0 0 1 8th Math Enrich 0 1 0 0 0 2 8th Science Enr 0 1 0 0

我有这个数据框:

    Course_2013     AP  Advanced    Vocational  Basic   ESL 
0   7th Math Enrich  0    1             0         0      0   
1   8th Math Enrich  0    1             0         0      0   
2   8th Science Enr  0    1             0         0      0   
3   Accounting I     0    0             0         1      0               
4   Accounting II    0    0             0         0      1   
我需要创建一个名为“category”的新列,该列在包含1的每行中包含列名称:

    Course_2013     AP  Advanced    Vocational  Basic   ESL category
0   7th Math Enrich  0    1             0         0      0   Advanced
1   8th Math Enrich  0    1             0         0      0   Advanced
2   8th Science Enr  0    1             0         0      0   Advanced
3   Accounting I     0    0             0         1      0   Basic              
4   Accounting II    0    0             0         0      1   ESL

让我们使用
apply
idxmax

df['category'] = df.iloc[:,1:].apply(lambda x: x.idxmax(), axis=1)
输出:

       Course_2013  AP  Advanced  Vocational  Basic  ESL  category
0  7th Math Enrich   0         1           0      0    0  Advanced
1  8th Math Enrich   0         1           0      0    0  Advanced
2  8th Science Enr   0         1           0      0    0  Advanced
3     Accounting I   0         0           0      1    0     Basic
4    Accounting II   0         0           0      0    1       ESL