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:
Original columns:
Result of head + to_dict
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
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:
Original columns:
Result of head + to_dict
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