在pandas中选择值= 1的列名

时间:2018-02-06 17:14:21

标签: python pandas

我有这个数据框:

    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

我需要创建名为“category”的新列,其中包含每行包含1的列的列名:

dotnet new --install "Microsoft.AspNetCore.SpaTemplates"

1 个答案:

答案 0 :(得分:1)

让我们使用applyidxmax

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