1

I have a DataFrame as follows:

Name | Year | Score | Time
Bob   2000   5       8
Jan   2000   6       6
Bob   2001   4       7
Jan   2001   8       8
Carl  2001   2       4
Bob   2002   5       7
Jan   2002   6       9
Carl  2002   7       4

As you can see, Carl has no entry for Year = 2000. I want to create a new row with that give Carl an entry in Year = 2000, but my actual DataFrame has 42 feature. What is the easiest method to do this?

1 Answer 1

3

Use DataFrame.unstack with DataFrame.stack:

df = df.set_index(['Name','Year']).unstack(fill_value=0).stack().reset_index()
print (df)
   Name  Year  Score  Time
0   Bob  2000      5     8
1   Bob  2001      4     7
2   Bob  2002      5     7
3  Carl  2000      0     0
4  Carl  2001      2     4
5  Carl  2002      7     4
6   Jan  2000      6     6
7   Jan  2001      8     8
8   Jan  2002      6     9
Sign up to request clarification or add additional context in comments.

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.