1

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

10
  • 3
    df['processed_comments']=df['comments'].str.split() Commented May 27, 2019 at 13:40
  • Hello Anky, Thanks for the quick response. I have a new list of lists and wanted to add a new column to the existing Dataframe. How do I do? The processed_comments, go through pre-processing and they are not the same as comments.split() Commented May 27, 2019 at 13:47
  • the processed_comments shown is exactly same as str.split() , however df['processed_comments'] = listOfList should work, when you say its not working what is the problem that you face while doing this? Commented May 27, 2019 at 13:50
  • 1
    If you have a function that does all the preprocessing on comments you can applyit like this: df['processed_comments'] = df['comments'].apply(function) Commented May 27, 2019 at 13:52
  • 1
    Should work if df and listOfList are the same len. Doublecheck that len(df) and len(listOfList) align Commented May 27, 2019 at 13:53

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.