Transforming lists in rows dataframe to strings

Question:

I have a dataset that has a column that has its values stored in lists. I want to transform the lists into strings, i.e. the values will go from [a, b, c] to "a b c" separated by spaces, in the same column.

I was able to partially deal with this problem with the function below:

def list_to_string(col):
    return " ".join(str(x) for x in col)

However i can’t make the space appear (first argument of the return), what could they do?

Problem after executing:

enter image description here

Original columns:

enter image description here

Result of head + to_dict

enter image description here

Asked By: Rafael Morais

||

Answers:

After your update:

df = pd.DataFrame({'cast': [['a, b, c'], ['d, e']]})
df['col'] = df['cast'].str[0].str.replace('s*,s*', ' ', regex=True)
print(df)

# Output
        cast    col
0  [a, b, c]  a b c
1     [d, e]    d e

Old answer

You can do:

df = pd.DataFrame({'cast': [['a', 'b', 'c'], ['d', 'e']]})
df['col'] = df['cast'].map(' '.join)
print(df)

# Output
        cast    col
0  [a, b, c]  a b c
1     [d, e]    d e
Answered By: Corralien