I have a dataframe that looks like the following. The rightmost column is my desired column:
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
How do I identify the first non-zero value in a group(Group
) and then create a column that retains the first non-zero value and show all else as zeroes?
I have been trying to leverage idxmax
for this as stated in this solution:
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()