0

I have two columns, one is a string, another is a list of strings.

How do I append the string to the list of strings?

What I tried:

df['Combined'] = df['string'] + df['ListOfStrings']

and

df['Combined'] = df['string'].to_list() + df['ListOfStrings']

Possible method:

Turn the string column into a list containing a single element, then try the method in my first attempt. But I haven't been able to figure out how to do this.

1
  • 1
    kindly share sample data, with expected output Commented May 7, 2020 at 2:59

2 Answers 2

1

I would do a list comprehension:

# sample data
df = pd.DataFrame({
    'string':['a','b','c'],
    'ListOfStrings':[['1','2'],['3','4'],['5']]
})

df['Combined'] = [a+[b] for a,b in zip(df['ListOfStrings'],df['string'])]

Output:

  string ListOfStrings   Combined
0      a        [1, 2]  [1, 2, a]
1      b        [3, 4]  [3, 4, b]
2      c           [5]     [5, c]
Sign up to request clarification or add additional context in comments.

Comments

0

You can enclose the df['string'] into list brackets, like this:

df['Combined'] = [df['string']] + df['ListOfStrings']

That way you won't have any issues performing this operation.

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.