簡體   English   中英

如何更改滿足給定條件的列值,同時保持該列不滿足條件的值

[英]How to change column values that meets a given condition while maintaining the values for that column that don't meet the condition

在我的 pandas dataframe 我有兩列我正在考慮X1Score 我打算重新計算並將值重新分配給列Score中的值,但相應的X1列小於500 Score中不滿足此條件的值應保持原樣。

目前,當我運行以下代碼時,它正確更改了滿足條件的Score的值X1列小於500 ,但未重新計算的Score的值被轉換為NaN而不是保持其原始值。

def do_not_try_this(df, card, feature, val):
    if df[df[feature]<val][feature].iloc[0] < val:
        current_score = card[feature]['points'].iloc[0]
        print('Current point', current_score)
        min_desired_score = card[feature].min()['points']
        print('Min point', min_desired_score)
        df.iloc[:,21] = (df[df[feature]<val]['scores'] + np.sum([current_score, min_desired_score])).astype(int)
    else:
        df['scores'] = df.iloc[:,21]
    
    return df

# Call Function
df = airtel_base_scores_df.copy(deep=True)
feature = 'X1'
val = 500

df = do_not_try_this(df, card, feature, val)

我該如何解決這個問題?

注意df.iloc[:,21] 表示列Score的值

我認為你需要改變:

df.iloc[:,21] = (df[df[feature]<val]['scores'] + np.sum([current_score, min_desired_score])).astype(int)

至:

df.iloc[:,21] = ( df['scores'].mask(df[feature]<val, df['scores'] + np.sum([current_score, min_desired_score]))).astype(int)

僅處理Series.mask中匹配條件的值。

暫無
暫無

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

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