簡體   English   中英

如何使用 pandas dataframe 列值用於多個 if-else 條件來計算其他列

[英]How to use pandas dataframe column value for multiple if-else conditions to calculate other columns

我有 dataframe,需要實現多個 ifelse 條件來過濾value column expo_value columncal_value column相乘

Input Dataframe

client_id      expo_value          value          cal_value
1                   126             30                 27.06
2                   135             60                 36.18
3                   144             120                 45
4                   162             30                 54.09
5                   153             90                 63.63
6                   181             120                 72.9
4                   207             30                  99.09
5                   315             90                 126.63
6                   414             120                 81.9

I have written function to filter multiple conditions and apply formula to calculate for that condition

def cal_df(df):
    
    if df[df['value'] <=30]:
        df= df['expo_value'] *30 + df['cal_value'] * 45
        return df
    elif df[(df['value'] <=60 and (df['value'] >=100)]:
        df= df['expo_value'] *60 + df['cal_value'] * 90
        return df
    elif df[(df['value'] <=100 and (df['value'] >=150)]:
        df= df['expo_value'] *100 + df['cal_value'] * 120
        return df
    else df[df['value'] <=10]:
        return np.nan



data = data.groupby('client_id').apply(lambda x:cal_df(x)).reset_index()
results should be stored as new column


### if am applying groupby condition am getting following error

Valueerror: The truth value of a series is ambiguous. Use a.empty ,a.bool(),a.item(),a.any() or a.all()

如果正在應用 groupby 條件,則會出現以下錯誤

#Valueerror:一個序列的真值是模棱兩可的。 使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

如果我明白你想做什么,你不需要做一個 groupby。 你可以這樣做:

data.loc[data['value'] <= 30, "new_column"] = data['expo_value']*30 + data['cal_value']*45

data.loc[(data['value'] <= 60) & (data['value'] >= 100), "new_column"] = data['expo_value']*60 + data['cal_value']*90

data.loc[(data['value'] <= 100) & (data['value'] >= 150), "new_column"] = data['expo_value']*100 + data['cal_value']*120

上面未捕獲的任何行中“new_column”的值默認為 NaN。 但是還有另一個問題,即最后兩行不匹配任何內容,因為某些內容不能同時低於 60 和高於 100,或者低於 100 和高於 150。它們是否都應該是 <= ?

嘗試這個

def func(value, expo_value, cal_value):
    if value <= 30: return expo_value * 30 + cal_value * 45
    elif value <= 60 and value >= 100: return expo_value * 60 + cal_value * 90
    elif value <= 100 and value >= 150:  return expo_value * 100 + cal_value * 120
    else: return np.nan

df['new_values'] = df[['value', 'expo_value', 'cal_value']].apply(lambda x: func(*x.values.tolist()), axis = 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM