代码之家  ›  专栏  ›  技术社区  ›  ak_slick

获取数据帧中每行最右边的非零值位置(非lambda方法)

  •  3
  • ak_slick  · 技术社区  · 7 年前

    我有一个很大的数据帧,如果右边有0,我需要得到其中每一行的最后一个零值索引。

    工作代码如下。输出正确。

    有没有一种方法可以矢量化这个代码(不使用lambda)

    示例代码:

    df = pd.DataFrame.from_dict(
        {'a': {0: 14, 1: 0, 2: 105, 3: 67},
         'b': {0: 67, 1: 0, 2: 0, 3: 63},
         'c': {0: 35, 1: 0, 2: 530, 3: 431},
         'd': {0: 500, 1: 0, 2: 0, 3: 500},
         'e': {0: 13, 1: 0, 2: 0, 3: 12},
         'f': {0: 123, 1: 0, 2: 0, 3: 0}}
    )
    
    # if row has no zeros use last index
    def func(row):
        # if row is all zeros return first index
        if sum(row == 0) == len(row):
            return row.index[0]
    
        # if row is all non zero return last index
        if sum(row != 0)== len(row):
            return row.index[-1]
    
        # else return index of right most non zero value
        return row.loc[row != 0].index[-1]
    
    df.apply(lambda row: func(row), axis=1)
    

    0    f
    1    a
    2    c
    3    e
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   ALollz    7 年前

    找到它不等于0的地方,然后找到第一个实例,它是最大值。

    df.ne(0).cumsum(1).idxmax(1)
    
    0    f
    1    a
    2    c
    3    e
    dtype: object