首页 > 解决方案 > 根据最多三列创建分类变量

问题描述

我有一个数据框,其中包含某些新闻文章的情绪概率,如下所示:

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

我现在想创建一个新的分类列,它告诉我,该行中的哪种情绪具有最高概率,并使用例如 ( 0, 1, 2) 对其进行编码以表示主要情绪。

最终输出应如下所示:

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列中的值与其他值进行比较以检查类别。但是应该有一种更疯狂的方式来做到这一点,对吧?

标签: pythonpython-3.xpandasdataframe

解决方案


用于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

推荐阅读