繁体   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