Python 为现有值之外的新值列创建循环
我希望在一个数据框中创建一个新列,指示比赛是以主场胜利、客场胜利还是平局结束 这是我当前使用的代码:Python 为现有值之外的新值列创建循环,python,python-3.x,pandas,dataframe,for-loop,Python,Python 3.x,Pandas,Dataframe,For Loop,我希望在一个数据框中创建一个新列,指示比赛是以主场胜利、客场胜利还是平局结束 这是我当前使用的代码: for value in df2: if value in df2['home_goals'] > df2['away_goals']: df2['result'] = 'H' elif value in df2['home_goals'] < df2['away_goals']: df2['result'] = 'A' els
for value in df2:
if value in df2['home_goals'] > df2['away_goals']:
df2['result'] = 'H'
elif value in df2['home_goals'] < df2['away_goals']:
df2['result'] = 'A'
else:
df2['result'] = 'D'
正如你所看到的,在这种情况下,主队或客队都赢了,所有的结果都是平局
有人能告诉我哪里出了问题吗
谢谢一种类似蟒蛇的方法可能是
import numpy as np
df2['result'] = np.where(df2['home_goals'] > df2['away_goals'], 'H',
np.where(df2['home_goals'] < df2['away_goals'], 'A', 'D'))
将numpy导入为np
df2['result']=np.其中(df2['home\u goals']>df2['away\u goals'],'H',
np.where(df2[“主场目标”]
使用chained
np.where()
命令。类似于您的方法是在数据帧上使用行应用函数
df = pd.DataFrame({'home':[2,1,0,2],'away':[1,3,1,2]})
def fun(x):
if x['home']>x['away']: return 'H'
elif x['home']<x['away']: return 'A'
else : return 'D'
df['result'] = df.apply(fun,axis=1)
df=pd.DataFrame({'home':[2,1,0,2],'away':[1,3,1,2]})
def fun(x):
如果x['home']>x['away']:返回'H'
您可以在此处使用elif x['home']
您也可以使用或循环,在代码中
中的值可能是原因,因此请删除它
def filter(row):
result =''
# Removed values in
if row['home_goals'] > row['away_goals']:
result = 'H'
elif row['home_goals'] < row['away_goals']:
result = 'A'
else:
result = 'D'
return result
df['result'] = df.apply(filter,axis=1)
def过滤器(行):
结果=“”
#删除中的值
如果行['home\u goals']>行['away\u goals']:
结果='H'
埃利夫行['home\u goals']|
您能提供一些数据吗?类似于dataframe.head(10)hanks已经尝试了其中的一些,并且已经解决了这个问题。非常感谢你的帮助!
condlist = [
df2["home_goals"] > df2["away_goals"],
df2["home_goals"] < df2["away_goals"],
]
choicelist = ["H", "A"]
df2["result"] = np.select(condlist, choicelist, "D")
condlist = [cond1, ..., condn]
choicelist = [choice1, ..., choicen]
# Here mapping is as follows:
# cond1 ⟶ choice1
# ...
# condn ⟶ choicen
np.select(condlist, choicelist, default='your_default_value')
def filter(row):
result =''
# Removed values in
if row['home_goals'] > row['away_goals']:
result = 'H'
elif row['home_goals'] < row['away_goals']:
result = 'A'
else:
result = 'D'
return result
df['result'] = df.apply(filter,axis=1)