根据最多三列创建分类变量



我有一个具有情感概率的数据框

sentimentPositive sentimentNegative sentimentNeutral 0.219640 0.010708 0.769652 0.539188 0.088198 0.372615 0.561837 0.264411 0.173752 0.570648 0.255499 0.173853 0.525263 0.097155 0.377582

我现在想创建一个告诉我的新分类列,该行中的情感具有最高的概率,并用例如(012)对于主要情感。

最终输出应该看起来像:

sentimentPositive sentimentNegative sentimentNeutral Sentiment 0.219640 0.010708 0.769652 2 0.539188 0.088198 0.372615 0 0.561837 0.264411 0.173752 0 0.570648 0.255499 0.173853 0 0.097155 0.525263 0.377582 1

我知道我可以通过:

获得列的最大值
df["max"] = df[["sentimentPositive","sentimentNegative","sentimentNeutral"]].max(axis=1)

,然后可以将max列中的值与其他值进行比较以检查类别。但是应该有一种更大的方法来做到这一点,对

使用numpy.argmax进行位置:

cols = ["sentimentPositive","sentimentNegative","sentimentNeutral"]
df["max"] = df[cols].values.argmax(axis=1)
#for columns names
#df["max"] = df[cols].idxmax(axis=1)
print (df)
   sentimentPositive  sentimentNegative  sentimentNeutral  max
0           0.219640           0.010708          0.769652    2
1           0.539188           0.088198          0.372615    0
2           0.561837           0.264411          0.173752    0
3           0.570648           0.255499          0.173853    0
4           0.097155           0.525263          0.377582    1

最新更新