Aavik
Aavik

Reputation: 1037

convert List of List to a single column in Dataframe

I have a pandas dataframe as below:

comments         tags
===============================
Hello I am fine  #askfine #tag1
How are you ?    #ask # tag2

I have the below list of lists:

[['Hello', 'I', 'am', 'fine'], ['How', 'are', 'you', '?']]

Now, I wanted to append the below list of lists as a single column to the original dataframe.

comments         tags             processed_comments
==============================================================
Hello I am fine  #askfine #tag1   ['Hello', 'I', 'am', 'fine']
How are you ?    #ask # tag2      ['How', 'are', 'you', '?']

How do I do?

df['processed_comments'] = listOfList is not working.

Thanks

Upvotes: 1

Views: 1250

Answers (1)

Mohit Motwani
Mohit Motwani

Reputation: 4792

l = [['Hello', 'I', 'am', 'fine'], ['How', 'are', 'you', '?']]

You can just use:

df['processed_comments'] = l
df
    comments         processed_comments
0   Hello I am fine [Hello, I, am, fine]
1   How are you ?   [How, are, you, ?]

Each list element is considered a value of the row. So make sure that the length of the list, i.e., the lists inside the list, is equal to the number of rows.

Upvotes: 2

Related Questions