How do I convert a list in a Pandas DF into a string?
You should certainly not convert to string before you transform the list. Try:
df['col'].apply(', '.join)
Also note that apply
applies the function to the elements of the series, so using df['col']
in the lambda function is probably not what you want.
Or, there is a native .str.join
method, but it is (surprisingly) a bit slower than apply
.
When you cast col
to str
with astype
, you get a string representation of a python list, brackets and all. You do not need to do that, just apply
join
directly:
import pandas as pd
df = pd.DataFrame({
'A': [['a', 'b', 'c'], ['A', 'B', 'C']]
})
# Out[8]:
# A
# 0 [a, b, c]
# 1 [A, B, C]
df['Joined'] = df.A.apply(', '.join)
# A Joined
# 0 [a, b, c] a, b, c
# 1 [A, B, C] A, B, C