'Collapsing rows based on condition in pandas
I have a dataframe like so:
Input:
Restaurant IP_Id IP_Time S_Code
McDonalds NaN 2021-03-28 03:01:05 4
McDonalds NaN 2021-03-28 03:01:05 5
McDonalds NaN 2021-03-28 03:01:05 6
McDonalds 101 2021-03-28 03:01:05 4
McDonalds 101 2021-03-28 03:01:05 5
Wendys 101 2021-03-28 03:01:05 4
Wendys 101 2021-03-28 03:01:05 4
I want to transform the dataframe to the following. For every instance where the IP_Id is the same for a specific restaurant at a specific time, I want to collapse the row and include a comma separated value for the S_Code.
Output:
Restaurant IP_Id IP_Time S_Code
McDonalds NaN 2021-03-28 03:01:05 4
McDonalds NaN 2021-03-28 03:01:05 5
McDonalds NaN 2021-03-28 03:01:05 6
McDonalds 101 2021-03-28 03:01:05 4, 5
Wendys 101 2021-03-28 03:01:05 4
I've tried grouping by Restaurant, IP_Id, and IP_Time, but it moves the records with Nan as the IP_Id
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
