0

I have a dataframe in pandas and one of my columns is a set of lists; however, some of the lists in the column have more elements than others:

df['Name'].head()

Output:

0 ['Andrew', '24']
1 ['James']
2 ['Billy', '19', 'M']
3 ['Grace', '42']
4 ['Amy']

Is it possible for me to concatenate each element in each list together, while still maintaining my df?

Desired output:

0 'Andrew24'
1 'James'
2 'Billy19M'
3 'Grace42'
4 'Amy'

I tried many different things; the closest I got was using the snip below but this concatenated all of the lists together in each record:

def concatenate_list_data(list):
    result= ''
    for element in list:
       result += str(element)
    return result
df['Name'] = concatenate_list_data(df['Name'])`
  • Does this answer your question? [Column of lists, convert list to string as a new column](https://stackoverflow.com/questions/45306988/column-of-lists-convert-list-to-string-as-a-new-column) – AMC Feb 13 '20 at 17:38
  • There’s also this question: https://stackoverflow.com/questions/37347725/converting-a-panda-df-list-into-a-string/37347837 – AMC Feb 13 '20 at 17:39

2 Answers2

2

Pandas offers a method for this, Series.str.join: df['Name'].str.join('').

AMC
  • 2,642
  • 7
  • 13
  • 35
  • I couldn't get that to change anything – Andrew Vitek Feb 13 '20 at 17:37
  • @AndrewVitek That’s really bizarre, what output did you get? Did you try printing the result, before assigning it back to the DataFrame? – AMC Feb 13 '20 at 17:40
  • You might want to redefine the column as `df['Name'] = df['Name'].str.join('')` I'm not sure the function has `inplace=True` as default behavior – Celius Stingher Feb 13 '20 at 17:44
  • @CeliusStingher Oh of course, what I shared wouldn’t change the DataFrame alone, it’s just a Series method. – AMC Feb 13 '20 at 17:45
0

Try this:

df['Name'].apply(lambda x: ''.join(x)

Output:

0    Andrew24
1       James
2    Billy19M
3     Grace42
4         Amy
Name: Name, dtype: object
CezarySzulc
  • 1,849
  • 1
  • 14
  • 30