Home > Enterprise >  How to convert a column into a list-column in pandas?
How to convert a column into a list-column in pandas?

Time:11-14

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']

CodePudding user response:

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']

CodePudding user response:

Very simple:

df['popular_tags'] = df['popular_tags'].str.split(', ')

Output:

>>> df
      popular_tags
0  ['A', 'B', 'C']
1  ['A', 'B', 'C']
  • Related