【问题标题】:Adding column of values to pandas DataFrame将值列添加到 pandas DataFrame
【发布时间】:2020-04-01 23:21:15
【问题描述】:

我正在做一个简单的情绪分析,并被困在我觉得很简单的事情上。我正在尝试添加具有一组值的新列,在此示例中为 compound 值。但是在 for 循环迭代之后,它为所有行添加相同的值,而不是为每次迭代添加一个值。 compound 值是 DataFrame 中的最后一列。应该有一个快速修复。谢谢!

for i, row in real.iterrows():
   real['compound'] = sid.polarity_scores(real['title'][i])['compound']


title   text    subject date                                                        compound
0   As U.S. budget fight looms, Republicans flip t...   WASHINGTON (Reuters) - The head of a conservat...   politicsNews    December 31, 2017   0.2263
1   U.S. military to accept transgender recruits o...   WASHINGTON (Reuters) - Transgender people will...   politicsNews    December 29, 2017   0.2263
2   Senior U.S. Republican senator: 'Let Mr. Muell...   WASHINGTON (Reuters) - The special counsel inv...   politicsNews    December 31, 2017   0.2263
3   FBI Russia probe helped by Australian diplomat...   WASHINGTON (Reuters) - Trump campaign adviser ...   politicsNews    December 30, 2017   0.2263
4   Trump wants Postal Service to charge 'much mor...   SEATTLE/WASHINGTON (Reuters) - President Donal...   politicsNews    December 29, 2017   0.2263

【问题讨论】:

  • real['compound'] = 分配整个列。你的意思是row['compound']?
  • 当我切换到row['compound'] 时,它对我不起作用。我想在每次迭代后添加一行。我最初的虽然是.append
  • 那个循环不是很地道,你读过 Pandas 文档吗?

标签: python pandas nlp sentiment-analysis


【解决方案1】:

IIUC:

real['compound'] = real.apply(lambda row: sid.polarity_scores(row['title'])['compound'], axis=1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 2020-12-28
    • 2015-04-25
    • 1970-01-01
    相关资源
    最近更新 更多