我这有熊猫df
id Vote1 Vote2 Vote3
123 Positive Negative Positive
223 Positive Negative Neutral
323 Positive Negative Negative
423 Positive Positive
我想添加另一个名为winner
的列
这将被设置为任何多数票,如果票数相等,则将设置第一票,如id=223所示
所以结果df应该是
^{pr2}$这可能与 Update Pandas Cells based on Column Values and Other Columns
我编写了一个函数并将其应用于df。它通常比普通的循环快一点。在
结果
^{pr2}$另一个,熊猫解决方案没有循环:
输出:
^{pr2}$解释
df.assign
是在原始数据帧的副本中创建列的一种方法,因此必须重新分配回df。列的名称是Winner
,因此是“winner=”。在接下来,使用^{} 嵌套if语句。。。np.哪里(条件、结果、其他)
你可以这样排:
结果:
^{pr2}$它可能不是最优雅的解决方案,但它相当简单。它使用numpy函数unique,该函数可以返回行中每个唯一字符串的计数。在
相关问题 更多 >
编程相关推荐