pandaps:在将dict拆分为列的同时应用函数

2024-10-06 16:26:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我定义函数如下。。。在

def getSentiment(x):
    vs = vaderSentiment
    col = vs(x['messages'].encode('utf-8', 'replace'))
    return col

我应用函数的数据帧的列每行包含单个字符串(两个示例)。。。在

^{pr2}$

当我使用。。。在

df['sentiment']=df.apply(getSentiment, axis=1)

函数产生的dict在新的情感列(两行示例)中转换为字符串格式。。。在

sentiment
{'compound': 0.4404, 'neg': 0.0, 'neu': 0.919, 'pos': 0.081} 
{'compound': 0.4404, 'neg': 0.0, 'neu': 0.256, 'pos': 0.744}

相反,是否有一种方法可以应用该函数,以便dict中的键值对作为单独的列(除了其他变量)返回,实际上如下所示:

compound    neg    neu      pos
0.4404      0.0    0.919    0.081
0.4404      0.0    0.256    0.744

除此之外,我尝试过使用DataFrame.from_dict并在这里搜索其他答案,但似乎没有什么是适用的。在


Tags: 函数字符串pos示例df定义defcol
1条回答
网友
1楼 · 发布于 2024-10-06 16:26:13

如果列sentiment的值是字符串,则可以^{}函数ast.literal_eval将它们转换为dictionary

import ast

print df

#                                           sentiment  tmp
#0  {'compound': 0.4404, 'neg': 0.0, 'neu': 0.919,...   aa
#1  {'compound': 0.4404, 'neg': 0.0, 'neu': 0.256,...  sss

print type(df['sentiment'][0])

#<type 'str'>

df1 = df['sentiment'].apply(lambda x: pd.Series(ast.literal_eval(x)))
print df1

#   compound  neg    neu    pos
#0    0.4404    0  0.919  0.081
#1    0.4404    0  0.256  0.744

如果列sentiment的值是字典

^{pr2}$

相关问题 更多 >