如何将列类型从列表更改为str pandas

时间:2017-09-29 17:19:29

标签: python pandas

我有一个数据框:

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]

我的值的dtype存储在" word"列是list。我希望这些值成为str。 我试过这个:

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

但它给我一个错误:

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

请告诉我解决问题的方法。

3 个答案:

答案 0 :(得分:2)

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

创建一个新列,其中包含逗号

连接的单词
df['word'] = df.word.str.join(',')

将覆盖现有列

答案 1 :(得分:1)

您收到密钥错误,因为您在加入列表值后尝试从df中选择数据。因此,请使用copy不改变现有数据框,而使用assign更改字列

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

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'

答案 2 :(得分:1)

非常接近。您正尝试从数据框中进行选择。只需删除一个额外的df和一组括号,你就在那里! :

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