Reputation: 134
In my dataframe, I have a column with data as a list like [cell, protein, expression], I wanted to convert it as a set of words like cell, protein, expression, it should applies to entire column of the dataframe. Please suggest the possible way to do it.
Upvotes: 1
Views: 1448
Reputation: 95
try this
data['column_name'] = data['column_name'].apply(lambda x: ', '.join(x))
Upvotes: 1
Reputation: 14063
The issue is that df['Final_Text']
is not a list but rather a string. try using ast.literal_eval
first:
import ast
from io import StringIO
# your sample df
s = """
,Final_Text
0,"['study', 'response', 'cell']"
1,"['cell', 'protein', 'effect']"
2,"['cell', 'patient', 'expression']"
3,"['patient', 'cell', 'study']"
4,"['study', 'cell', 'activity']"
"""
df = pd.read_csv(StringIO(s))
# convert you string of a list of to an actual list
df['Final_Text'] = df['Final_Text'].apply(ast.literal_eval)
# use a lambda expression with join to keep the text inside the list
df['Final_Text'] = df['Final_Text'].apply(lambda x: ', '.join(x))
Unnamed: 0 Final_Text
0 0 study, response, cell
1 1 cell, protein, effect
2 2 cell, patient, expression
3 3 patient, cell, study
4 4 study, cell, activity
Upvotes: 0