3

I have a dataset that looks like this:

df = pd.DataFrame(data= [[0,0,1],[1,0,0],[0,1,0]], columns = ['A','B','C'])

    A   B   C
0   0   0   1
1   1   0   0
2   0   1   0

I want to create a new column where on each row appears the value of the previous column where there is a 1:

    A   B   C value
0   0   0   1   C
1   1   0   0   A
2   0   1   0   B

2 Answers 2

3

Use dot:

df['value'] = df.values.dot(df.columns)

Output:

   A  B  C value
0  0  0  1     C
1  1  0  0     A
2  0  1  0     B
Sign up to request clarification or add additional context in comments.

Comments

2

Using pd.DataFrame.idxmax:

df['value'] = df.idxmax(1)

print(df)

   A  B  C value
0  0  0  1     C
1  1  0  0     A
2  0  1  0     B

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.