aristotle11
aristotle11

Reputation: 54

convert dataframe column of list to comma separated string in python

I've a dataframe df1

id     city       year
1       LA        [2012, 2013, 2014, 2015, 2026]
2       FL        []
3       TX        [2012, 2013, 2014]
4       NY        [2012]

How can I convert the column year that contains list into comma separated string?

Desired result:

id     city       year
1      LA         2012, 2013, 2014, 2015, 2016
2      FL         none
3      TX         2012, 2013, 2014
4      NY         2012

Note: The datatype of column year is string now.

Upvotes: 1

Views: 3019

Answers (3)

BENY
BENY

Reputation: 323236

Try with explode then groupby

df.year = df.year.explode().astype(str).groupby(level=0).agg(', '.join)

Upvotes: 1

ashkangh
ashkangh

Reputation: 1624

Another approach:

df.loc[:, 'year'] = df.year.apply(str).replace('[\[\]]', '', regex=True)

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195438

Try:

df["year"] = df["year"].apply(lambda x: ", ".join(map(str, x)))
print(df)

Prints:

   id city                          year
0   1   LA  2012, 2013, 2014, 2015, 2026
1   2   FL                              
2   3   TX              2012, 2013, 2014
3   4   NY                          2012

Or for none string:

df["year"] = (
    df["year"].apply(lambda x: ", ".join(map(str, x))).replace("", "none")
)
print(df)

Prints:

   id city                          year
0   1   LA  2012, 2013, 2014, 2015, 2026
1   2   FL                          none
2   3   TX              2012, 2013, 2014
3   4   NY                          2012

Upvotes: 2

Related Questions