Reputation: 75
How can I convert a normal column to a list column in a pandas
data frame? I tried something like this, but it doesn't work:
df['popular_tags'] = df['popular_tags'].to_list()
The column currently looks like this:
df['popular_tags']
0 'A', 'B', 'C'
1 'A', 'B', 'C'
The expected output would be a list column, such as:
df['popular_tags']
0 ['A', 'B', 'C']
1 ['E', 'F', 'G']
Upvotes: 0
Views: 444
Reputation:
Very simple:
df['popular_tags'] = df['popular_tags'].str.split(', ')
Output:
>>> df
popular_tags
0 ['A', 'B', 'C']
1 ['A', 'B', 'C']
Upvotes: 2
Reputation: 214
df = pd.DataFrame({'Popular Tags': ["'A', 'B', 'C'", "'E', 'F', 'G'"]})
print(df)
Popular Tags
0 'A', 'B', 'C'
1 'E', 'F', 'G'
df['Popular Tags']= df['Popular Tags'].astype('object')
df['Popular Tags'] = df['Popular Tags'].apply(lambda x: x.split(', '))
print(df)
Popular Tags
0 ['A', 'B', 'C']
1 ['E', 'F', 'G']
Upvotes: 1