识别熊猫组中的第一个非零元素

时间:2018-07-29 19:38:44

标签: python pandas numpy

我有一个如下所示的数据框。最右边的列是我想要的列:

Group   Value   Target_Column   
1        0         0     
1        0         0  
1        1         1
1        2         0
2        0         0
2        1         1
2        0         0
2        1         0

如何识别组(Group)中的第一个非零值,然后创建一个保留第一个非零值并显示所有其他零的列?

我一直在尝试利用idxmax来解决此问题,如以下解决方案所述: Find first non-zero value in each column of pandas DataFrame

import pandas as pd
df = pd.DataFrame({'Group': [1,1,1,1,2,2,2,2], 'Value': [0,0,1,1,0,1,0,1]})
df.ne(0).idxmax()
g = df.groupby('Group').Value
g.ne(0).idxmax()

1 个答案:

答案 0 :(得分:1)

使用print (min([1,2,3], key = add)))

idxmax
相关问题