Home > Mobile >  Convert single-word list to string
Convert single-word list to string

Time:06-07

I have a DataFrame column 'stem' with each cell being a single stemmed word inside of a list. I'd like to convert the single-item list to a string, but none of the functions I have seen online have worked. I've tried:

    for cell in countdf['stem']:
        cell = str(cell)

This doesn't seem to do anything either:

    for cell in countdf['stem']:
        cell = ''.join(cell)

In both cases, the column/cell types are still 'list' and are printed as ['word'] rather than word.

This one gives me an error 'TypeError: sequence item 0: expected str instance, list found' :

for row in countdf:
      countdf['stem'] = ''.join(countdf['stem'])

Following this link, I've tried:

for row in countdf:
      countdf['stem'] = ''.join(''.join(cell) for cell in countdf['stem'])

But this throws a memory error. This shouldn't be a memory-intensive process, so there must be something wrong here as well.

I know I'm applying the right operations here since these are the only ones being recommended anywhere, but surely there must be some issue in how I'm applying it. I'm genuinely lost here and any help would be greatly appreciated!

CodePudding user response:

IIUC, you can use apply

countdf['stem'] = countdf['stem'].apply(''.join)

If your column value contains integer

countdf['stem'] = countdf['stem'].apply(lambda lst: ''.join(map(str, lst)))

CodePudding user response:

Sounds like you can just use .str:

countdf['stem'] = countdf['stem'].str[0]

This is simple so it will be very fast. :)

  • Related