我有一个很大的数据框,并且如果右边有零,则需要获取其中每一行的最后一个零值索引.
如果行中没有零,则需要最后一个索引.
下面的工作代码.输出正确.
有没有办法向量化此代码(不使用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