我有这种代码,它检查A列中的值。如果满足条件,则代码检查同一行另一列中的值,然后从该列中复制值以替换A列中的值:
counter = 0
list_of_winners = []
for each in data.iterrows():
winner = data.iloc[counter, 5]
if winner == 'Red':
vitazr = data.iloc[counter, 0]
list_of_winners.append(vitazr)
elif winner == 'Blue':
vitazb = data.iloc[counter, 1]
list_of_winners.append(vitazb)
elif winner == 'Draw':
draw = str('Draw')
list_of_winners.append(draw)
else:
pass
counter += 1
该解决方案对我有效,我可以创建一个列表,然后将该列表放入原始Dataframe中并替换我循环遍历的值。
我想问的是...。还有其他更优雅,更简短的方法来攻击/解决此问题吗?
答案 0 :(得分:0)
您可以执行np.select
:
list_of_winners = np.select([data.iloc[:,5] == 'Red',
data.iloc[:,5] == 'Blue',
data.iloc[:,5] == 'Draw'],
[data.iloc[:,0], data.iloc[:, 1], 'Draw',
default=None
)