【问题标题】:New column based on threshold of next rows in Python Pandas基于 Python Pandas 中下一行阈值的新列
【发布时间】:2020-07-03 09:56:40
【问题描述】:

我有一个 pandas 数据框列,如下所示:

col1
200    
300    
400    
200    
500    
700    
0      
0      
60     
0      
0      

我正在尝试创建一个新列,该列是根据当前行值确定的,但也考虑了接下来的几行值。所以例如如果 (row_col1(i) > 60) & ((row_col1(i+1)+row_col1(i+2)+row_col1(i+3)) > 100),则在 col2 中写“是”。

col1   col2
200    yes
300    yes
400    yes
200    yes
500    yes
700    yes
0      no
0      no
60     no
0      no
0      no

关于如何实现这一点的任何想法?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以使用 .shift() 方法在 DataFrame 中处理此问题。示例请参阅此link

    这是使用ziplist 的一种方法:

    l1 = df['col1'].tolist()
    l2 = []
    for a,b,c,d in zip(l1,l1[1:],l1[2:],l1[3:]):
       if a>60 & (b+c+d)>100:
          l2 += ['yes']
       else:
          l2 += ['no']
    l2 += ['','',''] # cater for the last 3 entries. I've left it blank, you can decide whether to go for 'yes' or 'no' or 'NA'
    df['col2']= pd.Series(l2)
    

    【讨论】:

    • 这对我的分析很有帮助!它有点通用,因此我可以轻松地将其应用于其他场景。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2017-04-02
    • 2021-10-04
    • 1970-01-01
    • 2021-07-17
    相关资源
    最近更新 更多