Reputation: 54
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
Reputation: 323236
Try with explode
then groupby
df.year = df.year.explode().astype(str).groupby(level=0).agg(', '.join)
Upvotes: 1
Reputation: 1624
Another approach:
df.loc[:, 'year'] = df.year.apply(str).replace('[\[\]]', '', regex=True)
Upvotes: 1
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