返回满足熊猫条件的第一列号

时间:2020-06-24 19:52:02

标签: python pandas columnoperation

我有一个包含几列累积和的数据集。对于每一行,我想返回满足条件的第一列号。

玩具示例:

df = pd.DataFrame(np.array(range(20)).reshape(4,5).T).cumsum(axis=1)

>>> df
   0   1   2   3
0  0   5  15  30
1  1   7  18  34
2  2   9  21  38
3  3  11  24  42
4  4  13  27  46

例如,如果我想返回第一列,其值大于20。

所需的输出:

3
3
2
2
2

非常感谢,一如既往!

2 个答案:

答案 0 :(得分:2)

尝试使用idxmax

df.gt(20).idxmax(1)
Out[66]: 
0    3
1    3
2    2
3    2
4    2
dtype: object

答案 1 :(得分:1)

不像@YOBEN_S短,但是有效的是index.get_locfirst_valid_index的链接

df[df>20].apply(lambda x: x.index.get_loc(x.first_valid_index()), axis=1)
0    3
1    3
2    2
3    2
4    2
dtype: int64