我有一个大数据框,如果右边有零,我需要为其中的每一行获取最后一个零值索引。
如果行中没有零,我需要最后一个索引。
下面的工作代码。输出正确。
有没有办法向量化这段代码(不使用 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
最佳答案
找到它不等于 0 的地方,cumsum 然后找到它是最大值的第一个实例。
df.ne(0).cumsum(1).idxmax(1)
0 f
1 a
2 c
3 e
dtype: object
关于python - 为数据框中的每一行获取最右边的非零值位置(非 lambda 方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52895104/