OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Adding a new row to each group's last row in a dataframe [duplicate]

  • Thread starter Thread starter Laura
  • Start date Start date
L

Laura

Guest
My original dataframe is as below:

Code:
List = [['2024-05-25', 'Group 1', 'Year 1', 23466882], ['2024-05-25', 'Group 1', 'Year 2', 458397284], ['2024-05-25', 'Group 1', 'Year 3', 2344545], ['2024-05-25', 'Group 2', 'Year 1', 6662345], ['2024-05-25', 'Group 2', 'Year 2', 46342], ['2024-05-25', 'Group 3', 'Year 1', 34234], ['2024-05-25', 'Group 3', 'Year 2', 45222]]
df = pd.DataFrame(List, columns = ['Report_date', 'Product_group', 'Year', 'Sales'])

enter image description here

For each product group, if "Year 3" does not exist, a new row with sales of 11 000 should be added to the end.

The output should look like this:

enter image description here

My initial idea is to split the dataframe into each product group and add a new row if the sub- dataframe does not have any info for Year 3 but that approach does not seem to be optimal.

Any comment is appreciated. Thank you in advance!
<p>My original dataframe is as below:</p>
<pre><code>List = [['2024-05-25', 'Group 1', 'Year 1', 23466882], ['2024-05-25', 'Group 1', 'Year 2', 458397284], ['2024-05-25', 'Group 1', 'Year 3', 2344545], ['2024-05-25', 'Group 2', 'Year 1', 6662345], ['2024-05-25', 'Group 2', 'Year 2', 46342], ['2024-05-25', 'Group 3', 'Year 1', 34234], ['2024-05-25', 'Group 3', 'Year 2', 45222]]
df = pd.DataFrame(List, columns = ['Report_date', 'Product_group', 'Year', 'Sales'])
</code></pre>
<p><a href="https://i.sstatic.net/jafOmJFd.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/jafOmJFd.png" alt="enter image description here" /></a></p>
<p>For each product group, if "Year 3" does not exist, a new row with sales of 11 000 should be added to the end.</p>
<p>The output should look like this:</p>
<p><a href="https://i.sstatic.net/0bk46paC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/0bk46paC.png" alt="enter image description here" /></a></p>
<p>My initial idea is to split the dataframe into each product group and add a new row if the sub- dataframe does not have any info for Year 3 but that approach does not seem to be optimal.</p>
<p>Any comment is appreciated. Thank you in advance!</p>
 

Latest posts

Top