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

Remove elements stored as a list in a dataframe column from list structures and convert to a string

Is it possible to remove the comma separated date elements under the column df['date'] from the list structure and store as a string instead?
example dataframe:

df=pd.DataFrame({'date':[['2022-06-24'],['2021-07-07','2021-07-14'],\
                         ['2021-08-11','2021-12-17','2021-09-14','2022-02-15'],\
                             ['2019-08-19','2019-09-25'],\
                                 ['2013-05-16']]})

Output should look like this:

2022-06-24
2021-07-07,2021-07-14
2021-08-11,2021-12-17,2021-09-14,2022-02-15
2019-08-19,2019-09-25
2013-05-16

I tried:

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

df['date_2'] = [','.join(map(str, l)) for l in df['date']]

but not getting the desired output

>Solution :

Explode your lists then group by index and join all dates:

>>> df['date'].explode().groupby(level=0).agg(','.join)
0                                     2022-06-24
1                          2021-07-07,2021-07-14
2    2021-08-11,2021-12-17,2021-09-14,2022-02-15
3                          2019-08-19,2019-09-25
4                                     2013-05-16
Name: date, dtype: object

Alternative:

>>> df['date'].apply(lambda x: ','.join(x))
0                                     2022-06-24
1                          2021-07-07,2021-07-14
2    2021-08-11,2021-12-17,2021-09-14,2022-02-15
3                          2019-08-19,2019-09-25
4                                     2013-05-16
Name: date, dtype: object
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