1

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.

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

Another approach:

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

Comments

1

Try with explode then groupby

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.