我有 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/