python - 如何在Python中乘以数组中每个元素的每个值?

标签 python pandas graphlab

我正在使用 Graphlab,但我想这个问题也适用于 pandas。

import graphlab
sf = graphlab.SFrame({'id': [1, 2, 3], 'user_score': [{"a":4, "b":3}, {"a":5, "b":7}, {"a":2, "b":3}], 'weight': [4, 5, 2]})

我想创建一个新列,其中“user_score”中每个元素的值乘以“weight”中的数字。也就是说,

sf = graphlab.SFrame({'id': [1, 2, 3], 'user_score': [{"a":4, "b":3}, {"a":5, "b":7}, {"a":2, "b":3}], 'weight': [4, 5, 2]}, 'new':[{"a":16, "b":12}, {"a":25, "b":35}, {"a":4, "b":6}])

我尝试在下面编写一个简单的函数,但没有成功。有什么想法吗?

def trans(x, y):
    d = dict()
    for k, v in x.items():
        d[k] = v*y
    return d

sf.apply(trans(sf['user_score'], sf['weight']))

收到以下错误消息:

AttributeError: 'SArray' object has no attribute 'items'

最佳答案

我正在使用 pandas 数据框,但它也应该适用于您的情况。

import pandas as pd
df['new']=[dict((k,v*y) for k,v in x.items()) for x, y in zip(df['user_score'], df['weight'])]

输入数据框:

df
Out[34]: 
   id          user_score  weight
0   1  {u'a': 4, u'b': 3}       4
1   2  {u'a': 5, u'b': 7}       5
2   3  {u'a': 2, u'b': 3}       2

输出:

df
Out[36]: 
   id          user_score  weight                   new
0   1  {u'a': 4, u'b': 3}       4  {u'a': 16, u'b': 12}
1   2  {u'a': 5, u'b': 7}       5  {u'a': 25, u'b': 35}
2   3  {u'a': 2, u'b': 3}       2    {u'a': 4, u'b': 6}

关于python - 如何在Python中乘以数组中每个元素的每个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37540864/

相关文章:

Python - 将 csv 文件复制到 Dataframe(但跳过子文件夹)

python - 聚合组产生 Pandas 数据框

Python - 使用 itervalues() 时更改字典的值

python - 使用 Tkinter 文本编辑器突出显示错误

Python:使用 linecache 读取大量文件与普通文件访问 open()

python - graphlab-sframe : How to remove rows which have same ids and condition on a column?

ipython - Ipython笔记本属性错误: 'thread._local' object has no attribute 'hooks'

python - 名称错误 : name 'f2py' is not defined

python - 如何在Python中处理只包含小时、分钟和秒的字符串列

python - GraphLab 安装失败并出现未知错误