我有一个很大的数据帧,如果右边有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