【问题标题】:how to update a existing dataframe from a dictionary with keys as column and values forming the row in a loop如何从字典中更新现有数据框,其中键为列,值在循环中形成行
【发布时间】:2020-04-17 14:24:01
【问题描述】:
from nltk.sentiment.vader import SentimentIntensityAnalyzer    
sid = SentimentIntensityAnalyzer()
for i in range(len(X)):
    ss = sid.polarity_scores(X.loc[i,'essay'])
    X.from_dict(ss)

这里 X 是一个现有的数据框,我想添加 4 个新列,其名称是字典的键,值将形成行。

使用上面的代码我得到了错误:

ValueError: 如果使用所有标量值,则必须传递索引

但我不知道如何传递索引

样本字典:{'neg': 0.013, 'neu': 0.833, 'pos': 0.154, 'compound': 0.9694} 'neg','neu','pos','compound' 需要作为新列添加到现有数据框,并将其对应的值添加为行

【问题讨论】:

  • 请分享数据框样本和预期输出

标签: python dataframe dictionary


【解决方案1】:

from_dict 方法期望 iterable 或 dict 作为键的值。

X['neg'],X['neu'],X['pos'],X['compound'] = 'NaN','NaN','NaN','NaN'

for i in range(len(x)):
    ss = sid.polarity_scores(X.loc[i,'essay'])
    for j,k in ss.items():
        X.loc[i,j] = k

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    相关资源
    最近更新 更多