Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merge Dataframe rows based on the date

I have a dataframe that looks like this, It has the name of the company, the date and the title of a headline that was published regarding that company on that day. There are multiple headlines published on that single day and every single one of those headlines take up a different row even for the same date.

What I wish to do is merge all the title rows as per the date, so the Title column would represent ALL the headlines that were published on the day.
I tried doing it, but just messed up my dataframe.

Any help will be greatly appreciated!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can groupby and aggregate:

from datetime import date

import pandas as pd

df = pd.DataFrame(
    {
        "company": ["GOOG", "GOOG", "META", "META"],
        "date": [
            date(2022, 6, 1),
            date(2022, 6, 1),
            date(2022, 6, 1),
            date(2022, 6, 2),
        ],
        "title": ["google good", "google bad", "meta good", "meta bad"],
    }
)

df.groupby(["company", "date"]).aggregate(list).reset_index()

gives

  company        date                      title
0    GOOG  2022-06-01  [google good, google bad]
1    META  2022-06-01                [meta good]
2    META  2022-06-02                 [meta bad]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading