在其列之一上应用lambda后如何保存数据框?

时间:2019-02-18 08:20:33

标签: python pandas dataframe

我有这段代码是我编写的,用于修改数据框的一列,当我将其保存为CSV文件时,它正在保存旧的数据框。如何避免这种情况并将其另存为新数据框?

df2 = df_new.loc[(df_new['channel_name'] == self.channel) & (df_new['subtype'] == 'chat'), ['text']]        
print(df2['text'])
df2['sentiment'] = df2.apply(lambda row: TextBlob(row['text']).sentiment.polarity, axis=1)
print(df2.head())
df2.to_csv("new.csv", sep='\t', encoding='utf-8')

当我查看CSV文件时,它没有sentiment列。我该如何避免呢?使用print(df2.head())

                                                    text  sentiment
17337  Hi <!channel> -- interesting business news is ...    0.16456
17338  <@U04JNBU9W>: <@U04JL900N> is already working ...    0.00000

我可以在终端中查看数据框具有新列“观点”并应用了修改。但是当保存为CSV时,它是原始数据帧。 CSV文件输出

                                                    text     sentiment
17338   <@U04JNBU9W>: <@U04JL900N> is already working on it.    0.0
17339   Good news. This Chinese server is @ 120.39.251.37, by the way.  0.35
17340   Its good news. The task will continue to be part of the 2.0 project.    0.7
17341   good news, keep up the good work    0.7

0 个答案:

没有答案