簡體   English   中英

如何根據特定條件填充 dataframe 列中的值

[英]How to populate values in a column of dataframe based on a particular condition

我有以下 dataframe:

match   final_val   index  
False    0.002481   106278  
True     0.003135   106279  
True     0.000760   106280  
False    0.001313   106281  
True     0.000242   106282  

我希望創建一個名為finally_final_KL的新列,僅當下一行中的匹配為False時才從final_val列中獲取值。 例如,我想要這樣的東西:

match   final_val   index  finally_final_KL
False    0.002481   106278  
True     0.003135   106279  
True     0.000760   106280  0.000760
False    0.001313   106281  
True     0.000242   106282  

我寫了兩段代碼,都不起作用。 代碼 1:

for i in range(len(df['index'])):
    if i-1<0:
        continue
    elif df.match.iloc[i] == False:
        df.finally_final_KL.iloc[i-1] == df.final_val[i-1]
    else:
        df.finally_final_KL.iloc[i] == ""

我在最后一欄中沒有得到任何信息。 這段代碼的 output 是這樣的:

match   final_val   index  finally_final_KL
False    0.002481   106278  
True     0.003135   106279  
True     0.000760   106280  
False    0.001313   106281  
True     0.000242   106282  

代碼 2:

df['finally_final_KL'] = df['index'].apply(lambda x: df['final_val'].iloc[x] if df['match'].iloc[x+1]==False else "")

這會引發 Index 錯誤single positional indexer is out-of-bounds 我知道我得到了這個,因為代碼不適用於最后一行。 但是,如果我使用[x-1]而不是[x+1] ,它可以正常工作(我沒想到這次它可以為 x==0 工作)但是我當然沒有得到想要的 output。

如果有人能指出我的代碼中的錯誤或給我一個新的解決方案,我將不勝感激。

利用:

import numpy as np
df['finally_final_KL'] = np.where(df['match'].shift(-1) == False, df['final_val'], '')
print(df)

   match  final_val   index       finally_final_KL
0  False   0.002481  106278                       
1   True   0.003135  106279                       
2   True   0.000760  106280  0.0007599999999999999
3  False   0.001313  106281                       
4   True   0.000242  106282  

根據原始 DataFrame 中的數據類型,結果可能會有所不同,如上所示

您正在嘗試檢查下一行match 為此,您可以使用shift(-1) 然后你可以使用masknp.where

df['finally_final_XL'] = df['final_val'].mask(df['match'].shift(-1, fill_value=True), '')

或使用np.where

df['finally_final_XL'] = np.where(df['match'].shift(-1, fill_value=True),
                                  '', df['final_val'])

Output:

   match  final_val   index finally_final_XL
0  False   0.002481  106278                 
1   True   0.003135  106279                 
2   True   0.000760  106280          0.00076
3  False   0.001313  106281                 
4   True   0.000242  106282                 

暫無
暫無

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

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