Renton Renton - 3 years ago 235
Python Question

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.

Answer Source

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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download