0

My current df looks like that

Region Descript Material Input
UK Bottle #1 500
UK Cap #5 20
India Bottle #1 400
India Cap #5 2

would like to have a df2 to be like:

Region Descript Material Input
UK Bottle #1 500
UK Cap #5 20
UK other #7 NA
India Bottle #1 400
India Cap #5 2
India other #7 NA

I am new to python. Maybe there is a simple solution or an already similar case but i couldn't find anything

1 Answer 1

2

You can use groupby.tail to get the last row of each group, and modify them with assign, then concat it to the original DataFrame and sort by index while resetting it:

out = pd.concat([df,
                 df.groupby('Region', sort=False, as_index=False).tail(1)
                   .assign(Descript='other', Material='#7', Input='NA')]
               ).sort_index(ignore_index=True)

Output:

  Region Descript Material Input
0     UK   Bottle       #1   500
1     UK      Cap       #5    20
2     UK    other       #7    NA
3  India   Bottle       #1   400
4  India      Cap       #5     2
5  India    other       #7    NA
Sign up to request clarification or add additional context in comments.

2 Comments

One little thing: ...Input='NA'))]..one parenthesis was missing
Thanks @John, fixed it (you can actually remove the parentheses) ;)

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.