python - 根据最多三列创建分类变量
问题描述
我有一个数据框,其中包含某些新闻文章的情绪概率,如下所示:
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
列中的值与其他值进行比较以检查类别。但是应该有一种更疯狂的方式来做到这一点,对吧?
解决方案
用于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
推荐阅读
- javascript - 如何使用突变改变 vuex 状态
- flutter - 方法填充后如何返回列表,颤振
- python - 用于结束在列表中查找项目的循环的良好 Python 编程实践
- java - 基于条件的 CompletableFuture 失败
- c++ - 用 Vector3f 初始化 Vector4f
- python - 如何使用 BeautifulSoup、xpath 或 css 选择器获取第一个相关标签
- python - Python 和 MATLAB 中的 np.kron()
- laravel - 从 laravel 8 中的视图访问后端存储
- flutter - 如何仅增加文本小部件的高度
- html - 如何在Angular中的一行中设置列表