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

2024-10-03 13:25:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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')

计算出我需要什么,但当我不能结合欧洲的条件

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

enter image description here


Tags: lambda函数margintestdatadefeuramount
1条回答
网友
1楼 · 发布于 2024-10-03 13:25:12

您可以使用numpy.where创建一个数组,当region == 'Latin America'profir_margin_E不同时,该数组等于profir_margin_L_A,然后与amount_eur_y列相乘:

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

相关问题 更多 >