【问题标题】:Error while using sum() in Python SFrame在 Python SFrame 中使用 sum() 时出错
【发布时间】:2017-10-07 11:03:09
【问题描述】:

我是 python 新手,我正在对两个相似的 SFrame 执行基本的 EDA 分析。我有一本字典作为我的两列,我试图找出每个字典的最大值是否相同。最后,我想总结 Value_Match 列,这样我就可以知道有多少值匹配,但是我遇到了一个严重的错误并且我无法找到源。奇怪的是,我对两个 SFrame 都使用了相同的方法,其中只有一个给了我这个错误,而另一个没有。

我已尝试以此处给出的不同方式计算 max_func,但同样的错误仍然存​​在:getting-key-with-maximum-value-in-dictionary

我检查了列中是否存在任何可能的 NaN 值,但没有找到。

我已经坚持了一段时间,任何帮助将不胜感激。谢谢!

代码:

def max_func(d):
    v=list(d.values())
    k=list(d.keys())
    return k[v.index(max(v))]

sf['Max_Dic_1'] = sf['Dic1'].apply(max_func)
sf['Max_Dic_2'] = sf['Dic2'].apply(max_func)
sf['Value_Match'] = sf['Max_Dic_1'] == sf['Max_Dic_2']
sf['Value_Match'].sum()

错误:

RuntimeError                              Traceback (most recent call last)
<ipython-input-70-f406eb8286b3> in <module>()
----> 1 x = sf['Value_Match'].sum()
  2 y = sf.num_rows()
  3 
  4 print x
  5 print y

 C:\Users\rakesh\Anaconda2\lib\site-
 packages\graphlab\data_structures\sarray.pyc in sum(self)
 2216         """
 2217         with cython_context():
-> 2218             return self.__proxy__.sum()
 2219 
 2220     def mean(self):

C:\Users\rakesh\Anaconda2\lib\site-packages\graphlab\cython\context.pyc in 
__exit__(self, exc_type, exc_value, traceback)
 47             if not self.show_cython_trace:
 48                 # To hide cython trace, we re-raise from here
---> 49                 raise exc_type(exc_value)
 50             else:
 51                 # To show the full trace, we do nothing and let 
 exception propagate

RuntimeError: Runtime Exception. Exception in python callback function 
evaluation: 
ValueError('max() arg is an empty sequence',): 
Traceback (most recent call last):
File "graphlab\cython\cy_pylambda_workers.pyx", line 426, in 
graphlab.cython.cy_pylambda_workers._eval_lambda
File "graphlab\cython\cy_pylambda_workers.pyx", line 169, in 
graphlab.cython.cy_pylambda_workers.lambda_evaluator.eval_simple
File "<ipython-input-63-b4e3c0e28725>", line 4, in max_func
ValueError: max() arg is an empty sequence

【问题讨论】:

  • 错误不在sum 本身。 max_func 被懒惰地应用,问题是对于一个空字典,没有max...

标签: python dictionary graphlab


【解决方案1】:

为了调试这个问题,你必须查看堆栈跟踪。在我们看到的最后一行:

File "<ipython-input-63-b4e3c0e28725>", line 4, in max_func
ValueError: max() arg is an empty sequence

因此,Python 表示您的目标是计算 没有元素的列表的最大值。如果字典为空,就会出现这种情况。所以在你的一个数据框中可能有一个空字典{}

问题是如果字典为空该怎么办。您可能决定将None 返回到该案例中。

不过你写的代码太复杂了。一个更简单、更有效的算法是:

def max_func(d):
    if d:
        return max(d,key=d.get)
    else:
        # or return something if there is no element in the dictionary
        return None

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多