I have a dataframe that looks like this:

datetime hr rmssd neutral happy sad angry
2012-09-18 13:17:00 61.0 0.061420 0.884570 0.076952 0.001144 0.017392
2012-09-18 13:18:00 64.0 0.049663 0.931965 0.031468 0.000371 0.023774

What I want is to be able to create a new column that on each row assigns the name of the column which holds the biggest value: ie: in the first column there would be the emotion column stating 'neutral'. I tried iterating through each row like that:

for i in range(0,len(df3)):
    df3['emotion']=df3[['neutral','happy','sad','angry']].max()

but my resulting dataframe had an extra column named 'emotion' filled with NaN values. Note that I've deleted all of the NaN values from my df.

I also tried using iloc:

for i in range(0,len(df3)):
    df3['emotion']=df3.iloc[3:][i].max()

but zero luck there as well. Any ideas?

推荐答案

This should work without the for-loop. Based on this answer -> duplicate?

df3['emotion'] = df3[['neutral','happy','sad','angry']].idxmax(axis=1)

Python相关问答推荐

为什么调用函数的值和次数不同,递归在代码中是如何工作的?

OpenGL仅渲染第二个三角形,第一个三角形不可见

语法错误:文档. evaluate:表达式不是合法表达式

如何在一组行中找到循环?

使用polars. pivot()旋转一个框架(类似于R中的pivot_longer)

Scipy差分进化:如何传递矩阵作为参数进行优化?

将字节序列解码为Unicode字符串

按条件计算将记录拆分成两条记录

我怎样才能让深度测试在OpenGL中使用Python和PyGame呢?

有没有一种方法可以根据不同索引集的数组从2D数组的对称子矩阵高效地构造3D数组?

Django查询集-排除True值

逐个像素图像处理的性能问题(枕头)

如何在Python中使用Polars向SQLite数据库写入数据?

对齐多个叠置多面Seborn CAT图

Df.Drop_Duplates(),以极点表示?

Pandas 中的每行布尔运算

在matplotlib中将标题的一部分设置为粗体和正常

在Python中使用";swmm_api";包中的";lid_use";时出错?

Lxml xPASS在XML中的第一个标记下面找不到标记

如何在Replit Python中隐藏&行太长&警告(Pyright-Extended)?