我有一个看起来像这样的数据框:

        total   downloaded  avg_rating
id
1        2      2           5.0
2       12     12           4.5
3        1      1           5.0
4        1      1           4.0
5        0      0           0.0

我正在尝试添加一个新列,其中两个列的百分比差异很大,但仅适用于“下载”中没有0的列。

我正在尝试为此使用一个函数,如下所示:
def diff(ratings):
    if ratings[ratings.downloaded > 0]:
        val = (ratings['total'] - ratings['downloaded']) / ratings['downloaded']
    else:
        val = 0
    return val

ratings['Pct Diff'] = diff(ratings)

我收到一个错误:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-129-729c09bf14e8> in <module>()
      6     return val
      7
----> 8 ratings['Pct Diff'] = diff(ratings)

<ipython-input-129-729c09bf14e8> in diff(ratings)
      1 def diff(ratings):
----> 2     if ratings[ratings.downloaded > 0]:
      3         val = (ratings['total'] - ratings['downloaded']) /
ratings['downloaded']
      4     else:
      5         val = 0

~\Anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
    953         raise ValueError("The truth value of a {0} is ambiguous. "
    954                          "Use a.empty, a.bool(), a.item(), a.any() or
a.all()."
--> 955                          .format(self.__class__.__name__))
    956
    957     __bool__ = __nonzero__

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

有人可以帮助我了解此错误的含义吗?

另外,这对于apply函数是否是一个很好的应用程序?我可以在申请中使用条件吗?在这种情况下,我将如何使用它?

最佳答案

发生错误的原因是您试图进行逐行(向量化计算),但是实际上在您的函数diff()ratings[ratings.downloaded > 0]返回数据帧的子集,并且在if之前是不明确的。错误消息反射(reflect)了这一点。

您可能希望查看Indexing and Selecting Data。以下解决方案通过在开始时将默认值设置为0来进行设置。

import pandas as pd

df = pd.DataFrame([[2, 2, 5.0], [12, 12, 4.5], [10, 5, 3.0],
                   [20, 2, 3.5], [3, 0, 0.0], [0, 0, 0.0]],
                  columns=['total', 'downloaded', 'avg_rating'])

df['Pct Diff'] = 0
df.loc[df['downloaded'] > 0, 'Pct Diff'] = (df['total'] - df['downloaded']) / df['total']

#   total   downloaded  avg_rating  Pct Diff
# 0 2   2   5.0 0.0
# 1 12  12  4.5 0.0
# 2 10  5   3.0 0.5
# 3 20  2   3.5 0.9
# 4 3   0   0.0 0.0
# 5 0   0   0.0 0.0

关于python - ValueError:DataFrame的真值不明确,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48481223/

10-12 00:49