【问题标题】:pandas find start and stop point of non-null values熊猫找到非空值的起点和终点
【发布时间】:2022-01-03 01:12:12
【问题描述】:

我想找到一列的起点和终点并标记它们,如下所示:

value flag
NaN NaN
NaN NaN
1 start
2 NaN
1 NaN
3 NaN
2 stop
NaN NaN
1 start
2 stop

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:
    • 当当前值为notnull 且前一个值为isnull 时,出现start
    • 当当前值为notnull 且下一个值为isnull 时,出现stop

    使用shift 生成这些条件并使用loc 进行分配:

    start = df.value.notnull() & df.value.shift().isnull()
    stop = df.value.notnull() & df.value.shift(-1).isnull()
    
    df.loc[start, 'flag'] = 'start'
    df.loc[stop, 'flag'] = 'stop'
    
    #    value   flag
    # 0    NaN    NaN
    # 1    NaN    NaN
    # 2    1.0  start
    # 3    2.0    NaN
    # 4    1.0    NaN
    # 5    3.0    NaN
    # 6    2.0   stop
    # 7    NaN    NaN
    # 8    1.0  start
    # 9    2.0   stop
    

    或者使用mask进行分配:

    df['flag'] = df['flag'].mask(start, 'start')
    df['flag'] = df['flag'].mask(stop, 'stop')
    
    【解决方案2】:

    在这里,我遍历行并使用一个标志来指示我们是否开始。

    start_flag = 0
    for index, row in df.iterrows():
      if row['val'].isnull():
        df.loc[index, 'flag'] = "NaN"
        start_flag = 0
      else:
        if start_flag == 0:
          df.loc[index, 'flag'] = "start"
          start_flag = 1
        else:
          if (index < df.shape[0]-1 and df.loc[index+1, 'val'].isnull()) or index == df.shape[0]-1:
             df.loc[index, 'flag'] = "stop"
    

    【讨论】:

    • 请不要使用迭代,除非您没有其他选择。遍历所有行是个坏主意。它既昂贵又缓慢
    【解决方案3】:

    这是你需要的:

    # Auxiliar columns to detect start and end
    df['Past'] = df['Value'].shift(-1)
    df['Future'] = df['Value'].shift(1)
    
    # Auxiliar function to complete new column
    def Find_start_stop_Null(row):
        flag = np.nan
        if ((not pd.isnull(row['Value'])) and (pd.isnull(row['Future']))):
            flag = 'start'
        elif ((not pd.isnull(row['Value'])) and (pd.isnull(row['Past']))):
            flag = 'stop'
        return flag
    
    df['flag'] = df.apply(lambda row: Find_start_stop_Null(row), axis=1)
    # Drop unnecessary columns
    df = df.drop('Past', axis=1)
    df = df.drop('Future', axis=1)
    

    【讨论】:

      猜你喜欢
      • 2017-08-25
      • 2021-09-19
      • 2018-10-05
      • 1970-01-01
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 2020-03-21
      相关资源
      最近更新 更多