gpt4 book ai didi

python - 将函数应用于行,将字典解压缩为多列

转载 作者:行者123 更新时间:2023-12-01 02:02:55 24 4
gpt4 key购买 nike

我正在对存储在 pandas 列中的语料库使用 NLTK 的 SentimentIntensityAnalyzer()。使用 .polity_scores() 返回一个包含四个键及其值(neg、neu、pos 和compound)的字典。

我想迭代数据帧中的每一行,计算 join_corpus['body] 中包含的语料库的极性分数,并将生成的字典解压到数据帧中的四列中。我无法找到将多个键:值对解压到 pandas 中的列中的方法,因此我不得不使用以下 for 循环:

for index, row in joined_corpus.iterrows():
sentiment = sid.polarity_scores(row['body'])
joined_corpus.loc[index, 'neg'] = sentiment['neg']
joined_corpus.loc[index, 'neu'] = sentiment['neu']
joined_corpus.loc[index, 'pos'] = sentiment['pos']
joined_corpus.loc[index, 'compound'] = sentiment['pos']
print("sentiment calculated for "+ row['subreddit'] + "of" + str(sentiment))

这会产生如下输出:

sentiment calculated for 1200isplentyof{'neg': 0.067, 'neu': 0.745, 'pos': 0.188, 'compound': 1.0}
sentiment calculated for 2007scapeof{'neg': 0.092, 'neu': 0.77, 'pos': 0.138, 'compound': 0.9998}
sentiment calculated for 2b2tof{'neg': 0.123, 'neu': 0.768, 'pos': 0.109, 'compound': -0.9981}
sentiment calculated for 2healthbarsof{'neg': 0.096, 'neu': 0.762, 'pos': 0.142, 'compound': 0.9994}
sentiment calculated for 2meirl4meirlof{'neg': 0.12, 'neu': 0.709, 'pos': 0.171, 'compound': 0.9997}
sentiment calculated for 3DSof{'neg': 0.054, 'neu': 0.745, 'pos': 0.201, 'compound': 1.0}
sentiment calculated for 3Dprintingof{'neg': 0.056, 'neu': 0.812, 'pos': 0.131, 'compound': 1.0}
sentiment calculated for 3dshacksof{'neg': 0.055, 'neu': 0.804, 'pos': 0.141, 'compound': 1.0}
sentiment calculated for 40kLoreof{'neg': 0.123, 'neu': 0.747, 'pos': 0.13, 'compound': 0.9545}
sentiment calculated for 49ersof{'neg': 0.098, 'neu': 0.715, 'pos': 0.187, 'compound': 1.0}

但是,显然,这很慢,因为它不使用 pandas 内置的 apply 命令。在这种情况下有没有办法避免 for 循环?

最佳答案

通过使用应用

sentiment = df['body'].apply(lambda x : sid.polarity_scores(x))
df=pd.concat([df,sentiment.apply(pd.Series)],1)

那么,

"sentiment calculated for "+df['subreddit']+'of'+ sentiment.astype(str)

关于python - 将函数应用于行,将字典解压缩为多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49412303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com