Reputation: 6197
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.
Upvotes: 0
Views: 737
Reputation: 150735
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]
Upvotes: 1
Reputation: 336
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.
Upvotes: 0