Column of lists, convert list to string as a new column

List Comprehension

If performance is important, I strongly recommend this solution and I can explain why.

df['liststring'] = [','.join(map(str, l)) for l in df['lists']]
df

                lists    liststring
0  [1, 2, 12, 6, ABC]  1,2,12,6,ABC
1     [1000, 4, z, a]    1000,4,z,a

You can extend this to more complicated use cases using a function.

def try_join(l):
    try:
        return ','.join(map(str, l))
    except TypeError:
        return np.nan

df['liststring'] = [try_join(l) for l in df['lists']]

Series.apply/Series.agg with ','.join

You need to convert your list items to strings first, that’s where the map comes in handy.

df['liststring'] = df['lists'].apply(lambda x: ','.join(map(str, x)))

Or,

df['liststring'] = df['lists'].agg(lambda x: ','.join(map(str, x)))
df
                lists    liststring
0  [1, 2, 12, 6, ABC]  1,2,12,6,ABC
1     [1000, 4, z, a]    1000,4,z,a

pd.DataFrame constructor with DataFrame.agg

A non-loopy/non-lambda solution.

df['liststring'] = (pd.DataFrame(df.lists.tolist())
                      .fillna('')
                      .astype(str)
                      .agg(','.join, 1)
                      .str.strip(','))

df
                lists    liststring
0  [1, 2, 12, 6, ABC]  1,2,12,6,ABC
1     [1000, 4, z, a]    1000,4,z,a

Leave a Comment