Python 在计算字段中添加不正确的值

Python 在计算字段中添加不正确的值,python,pandas,numpy,dataframe,Python,Pandas,Numpy,Dataframe,我有一个函数,它应该添加一个新的包含利润的列 def profit(data): for index, row in data.iterrows(): #print row[0] profir_margin_L_A = 0.04 profir_margin_E = 0.02 if row[2]== 'Latin America': # row['profit'] = data.apply(lambda row:

我有一个函数,它应该添加一个新的包含利润的列

def profit(data):
    for index, row in data.iterrows():
        #print row[0]
        profir_margin_L_A = 0.04
        profir_margin_E = 0.02
        if row[2]== 'Latin America':
#       row['profit'] = data.apply(lambda row: row[8]* profir_margin_L_A)
            data['profit'] = data['amount_eur_y'] * profir_margin_L_A

        else:
#             row['profit'] = data.apply(lambda row: row[8]* profir_margin_E)
            data['profit'] = data['amount_eur_y'] * profir_margin_E
    return data
所有行的回报率为0.02%,而不仅仅是欧洲

我也试过了,但只适用于一种情况

test['profit'] = (test['amount_eur_y']*profir_margin_L_A).where(test['region'] == 'Latin America')
计算了我所需要的,但当我不能结合欧洲的条件时

最后,我需要一个数据框架与正确的利润计算


您可以使用
numpy.where
创建一个数组,该数组等于
profir\u margin\u L\u A
地区==“拉丁美洲”
profir\u margin\u E
否则,然后将其与
金额
列相乘:

test['profit'] = test['amount_eur_y'] * pd.np.where(test['region'] == 'Latin America', profir_margin_L_A, profir_margin_E)