python - 根据其他三列的多数值设置 pandas 数据框获胜者列值

标签 python pandas

我有 pandas df 这样

id  Vote1     Vote2      Vote3 
123 Positive  Negative   Positive
223 Positive  Negative   Neutral 
323 Positive  Negative   Negative  
423 Positive  Positive             

我想添加另一列名为 winner 这将被设置为多数票数,如果出现平局,则将设置第一票,如 id= 223 所示

所以结果 df 应该是

id  Vote1     Vote2      Vote3      Winner
123 Positive  Negative   Positive   Positive
223 Positive  Negative   Neutral    Positive
323 Positive  Negative   Negative   Negative 
423 Positive  Positive              Positive

这可能与 Update Pandas Cells based on Column Values and Other Columns

最佳答案

您可以逐行执行此操作,如下所示:

import pandas as pd
import numpy as np

# Create the dataframe
df = pd.DataFrame()
df['id']=[123,223,323,423]
df['Vote1']=['Positive']*4
df['Vote2']=['Negative']*3+['Positive']
df['Vote3']=['Positive','Neutral','Negative','']

mostCommonVote=[]
for row in df[['Vote1','Vote2','Vote3']].values:
    votes, values = np.unique(row, return_counts=True)
    if np.all(values<=1):
            mostCommonVote.append( row[0] )
    else:
        mostCommonVote.append( votes[np.argmax(values)] )

df['Winner'] = mostCommonVote

结果:

 df:
    id     Vote1     Vote2     Vote3    Winner
0  123  Positive  Negative  Positive  Positive
1  223  Positive  Negative   Neutral  Positive
2  323  Positive  Negative  Negative  Negative
3  423  Positive  Positive            Positive

这可能不是最优雅的解决方案,但它非常简单。它使用 numpy 函数unique,它可以返回行的每个唯一字符串的计数。

关于python - 根据其他三列的多数值设置 pandas 数据框获胜者列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43990485/

相关文章:

python - 根据列中的值生成子数据框

python - 对 Python 字典的可切换点访问?

python - Py 安装程序 "ValueError: too many values to unpack"

python - Pandas:获取每一行的 ohlc 数据

python - 为什么如果我将多个空的 Pandas 系列放入 hdf5 hdf5 的大小如此巨大?

python - 当小数>=1时,pandas/numpy round()如何工作?

python - 从字符串中删除多个单词的更好方法?

python - django 导入错误 - 没有名为 core.management 的模块

python - matplotlib 不在散点图中显示图例

python - 如何根据 Y 列中的值有条件地修改 X 列中的单元格