I am working on Python Pandas.
I have a pandas dataframe with columns like this:
| ID | Cities |
|---|---|
| 1 | New York |
| 1 | '' |
| 1 | Atlanta |
| 2 | Tokyo |
| 2 | Kyoto |
| 2 | '' |
| 3 | Paris |
| 3 | Bordeaux |
| 3 | '' |
| 4 | Mumbai |
| 4 | '' |
| 4 | Bangalore |
| 5 | London |
| 5 | '' |
| 5 | Bermingham |
Note the empty cells in the column are either empty string ('') or Nan or None. (For simplicity lets just say they are empty strings ('')).
And I want the result to be like this:
| ID | Cities |
|---|---|
| 1 | New York, Atlanta |
| 2 | Tokyo, Kyoto |
| 3 | Paris, Bordeaux |
| 4 | Mumbai, Bangalore |
| 5 | London, Bermingham |
In short, I want to group by ID and then getting the list (by removing the empty strings).
I have a sample code for this but it actually gives me result with empty strings, I want to remove empty strings.
dataFrame.groupby(['ID'], as_index=False)
.agg({'Cities': lambda x: x.tolist()})
It gives me result like this:
| ID | Cities |
|---|---|
| 1 | New York, ,Atlanta |
| 2 | Tokyo, Kyoto, |
| 3 | Paris, Bordeaux, |
| 4 | Mumbai, , Bangalore |
| 5 | London, , Bermingham |
But I dont want empty strings...
Please help me here.
Thank you so much for you help.