[英]Get rightmost non-zero value position for each row in dataframe (non lambda method)
我有一个大数据框,如果右边有零,我需要为其中的每一行获取最后一个零值索引。
如果行中没有零,我需要最后一个索引。
下面的工作代码。 输出正确。
有没有办法矢量化这段代码(不使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.