Renton
Renton

Reputation: 83

How to change column type from list to str pandas

I have a Data Frame:

df = pd.DataFrame({'id':[1,2,3],'word':[['one', 'two', 'four'],
                                    ['five', 'six', 'nine'], 
                                    ['eight', 'eleven', 'ten']]})

    id  word
0   1   [one, two, four]
1   2   [five, six, nine]
2   3   [eight, eleven, ten]

The dtype of my values stored in "word" column is list. I want that values to become str instead. I've tried this:

df2 =  df[df.word.map(lambda y: " ".join(y))]

But it raised me an error:

KeyError: "['one two four' 'five six nine' 'eight eleven ten'] not in index"

Please, advise me something to solve my problem.

Upvotes: 0

Views: 97

Answers (3)

Bharath M Shetty
Bharath M Shetty

Reputation: 30605

You are getting key error because you are trying to select the data from df after joining the list values. So instead use copy for not altering existing dataframe and assign to change the word column

df2 = df.copy().assign(word = df.word.map(lambda y: " ".join(y)))

Or

df2 = df.copy().assign(word = df.word.str.join(" "))

df2
  id              word
0   1      one two four
1   2     five six nine
2   3  eight eleven ten
df2['word'][0]
'one two four'

Upvotes: 1

Haleemur Ali
Haleemur Ali

Reputation: 28243

df['word_str'] = df.word.str.join(',')

creates a new column with the words joined by comma

df['word'] = df.word.str.join(',')

will overwrite the existing column

Upvotes: 2

A.Kot
A.Kot

Reputation: 7903

Very close. You're trying to select from the dataframe. Just remove an extra df and set of brackets and you're there! :

df2 =  df.word.map(lambda y: " ".join(y))

Upvotes: 1

Related Questions