根据条件识别具有行中第一个值的列

我有数据框,我想在其中标识每行的列,该列具有与条件相对应的第一个值。在下面的例子中,我想创建一个新列,它标识每行中小于或等于 1 的第一个值,并给出相应的列名称。


df = pd.DataFrame({'A': [1.5,2,4,0.5], 'B' : [2,1,3,0.25], 'C': [3,1,1,1], 'D': [2,2,3,1]})

df

    A    B      C   D

0   1.5  2.00   3   2

1   2.0  1.00   1   2

2   4.0  3.00   1   3

3   0.5  0.25   1   1

我可以创建一个面具来检查情况。


temp = df<=1

temp

    A       B       C       D

0   False   False   False   False

1   False   True    True    False

2   False   False   True    False

3   True    True    True    True

然后我可以使用以下内容来确定列。


df['New_col'] = temp.idxmax(axis = 1)

df

    A    B      C   D   New_col

0   1.5  2.00   3   2   A

1   2.0  1.00   1   2   B

2   4.0  3.00   1   3   C

3   0.5  0.25   1   1   A

该代码正确识别了 New_col 中的列(第 0 行除外),因为第 0 行中的所有值都大于 1。如何为 New_col 中的第 0 行获取 NaN 而不是 A?


以下是所需的输出。


    A    B      C   D   New_col

0   1.5  2.00   3   2   NaN

1   2.0  1.00   1   2   B

2   4.0  3.00   1   3   C

3   0.5  0.25   1   1   A


森林海
浏览 244回答 1
1回答

ITMISS

用于检查行上any(1)是否有 a并进行屏蔽:Truewheredf['New_col'] = temp.idxmax(axis = 1).where(temp.any(1))输出:&nbsp; &nbsp; &nbsp;A&nbsp; &nbsp; &nbsp;B&nbsp; C&nbsp; D New_col0&nbsp; 1.5&nbsp; 2.00&nbsp; 3&nbsp; 2&nbsp; &nbsp; &nbsp;NaN1&nbsp; 2.0&nbsp; 1.00&nbsp; 1&nbsp; 2&nbsp; &nbsp; &nbsp; &nbsp;B2&nbsp; 4.0&nbsp; 3.00&nbsp; 1&nbsp; 3&nbsp; &nbsp; &nbsp; &nbsp;C3&nbsp; 0.5&nbsp; 0.25&nbsp; 1&nbsp; 1&nbsp; &nbsp; &nbsp; &nbsp;A
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python