首页 > 解决方案 > Pandas 根据条件在多列中找到第一个非零条目

问题描述

我有一个这样的数据框 -

   Alpha    Id   Col1   Col2    Col3    Col4
0   a      Col3   0      0       10      34
1   b      Col2   0      5       0       4
2   c      Col1   16     0       3       0
3   d      Col2   0      0       0       9
4   e      Col3   0      0       18      0
5   f      Col1   0      14      0       29

对于每一行,我需要找到在指定的列之后出现的第一个非零值的列名ID

这样生成的数据框看起来像这样 -

   Alpha    Id     Col1   Col2  Col3    Col4    Result
0   a       Col3    0      0    10        34    Col4
1   b       Col2    0      5    0         4     Col4
2   c       Col1    16     0    3         0     Col3
3   d       Col2    0      0    0         9     Col4
4   e       Col3    0      0    18        0     0
5   f       Col1    0      14   0         29    Col2

我知道idxmax()可用于连续获取第一个非零条目。但是我怎样才能在这里指定条件呢?

提前感谢任何解决方案/提示。

标签: pythonpandasdataframe

解决方案


利用:

#compare last 4 columns by Id column with broadcasting
a = df.columns[-4:].to_numpy() == df['Id'].to_numpy()[:, None]
#print (a)

#shifting by 1 values, check next matching by cumulative sum and compare for not equal
m1 = np.cumsum(a[:, :-1], axis=1) != 0
#compare last 3 columns
m2 = df.iloc[:, -3:].ne(0)
#chain masks by bitwise AND
m = m1 & m2
#get values of index if at least one True per row else 0
df['new'] = np.where(m.any(axis=1), m.idxmax(axis=1), 0)
print (df)
  Alpha    Id  Col1  Col2  Col3  Col4   new
0     a  Col3     0     0    10    34  Col4
1     b  Col2     0     5     0     4  Col4
2     c  Col1    16     0     3     0  Col3
3     d  Col2     0     0     0     9  Col4
4     e  Col3     0     0    18     0     0
5     f  Col1     0    14     0    29  Col2

推荐阅读