一个字符串到句子数据框架熊猫的数组

时间:2017-02-13 18:40:54

标签: python arrays pandas dataframe

我的数据框看起来像

Phrase                                           Sentiment
[seri, escapad, demonstr, adag, good, goos]         1
[seri, escapad, demonstr, adag, good, goos]         2

当我使用命令df.dtypes

Phrase       object
Sentiment     int64
dtype: object

我需要获得如下数据框:

Phrase                                           Sentiment
seri escapad demonstr adag good goos            1
seri escapad demonstr adag good bad             2

我试过这段代码

df['Phrase'] = df[df.Phrase.map(lambda x: ','.join(x))]

id应该做什么

3 个答案:

答案 0 :(得分:2)

几乎正确 - 你有一个额外的df[层。试试这个:

df['Phrase'] = df.Phrase.map(lambda x: ' '.join(x))

您已经返回了要用于替换Phrase的列,但之后您尝试使用其值进行索引,这会产生错误。

答案 1 :(得分:1)

我认为你非常接近。以下行应该可以解决问题:

df['Phrase'] = df['Phrase'].map(lambda x: ' '.join(x))

答案 2 :(得分:1)

使用','而不是','

你可以在没有lambda的情况下这样做:

df['Phrase'] = df.Phrase.apply(', '.join)

使用lambda:

df['Phrase'] = df.Phrase.apply(lambda x: ', '.join(x))