pandas 错误>序列的真值不明确,请使用.empty、.bool()、.item()、.any()或.all()

polhcujo  于 2023-02-27  发布在  其他
关注(0)|答案(2)|浏览(221)

我想对Pandas Dataframe (数组)中值仅为1的每一行的列进行 * 水平 * 求和。我不是对列进行垂直求和。我是对它们进行水平求和。似乎互联网上的每个示例都对列进行垂直求和。
下面是我的简单函数:

def isOne(x):
    if (x == 1):
        return 1 
    else:
        return 0

下面是我的apply语句

df.apply(lambda column: sum(isOne(column)), axis=1)

这是我收到的错误:

ValueError                                Traceback (most recent call last)
Cell In[30], line 2
      1 tally = 0
----> 2 df.apply(lambda column: sum(isOne(column)), axis=1
      3         )

File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\frame.py:9568, in DataFrame.apply(self, func, axis, raw, result_type, args, **kwargs)
   9557 from pandas.core.apply import frame_apply
   9559 op = frame_apply(
   9560     self,
   9561     func=func,
   (...)
   9566     kwargs=kwargs,
   9567 )
-> 9568 return op.apply().__finalize__(self, method="apply")

File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\apply.py:764, in FrameApply.apply(self)
    761 elif self.raw:
    762     return self.apply_raw()
--> 764 return self.apply_standard()

File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\apply.py:891, in FrameApply.apply_standard(self)
    890 def apply_standard(self):
--> 891     results, res_index = self.apply_series_generator()
    893     # wrap results
    894     return self.wrap_results(results, res_index)

File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\apply.py:907, in FrameApply.apply_series_generator(self)
    904 with option_context("mode.chained_assignment", None):
    905     for i, v in enumerate(series_gen):
    906         # ignore SettingWithCopy here in case the user mutates
--> 907         results[i] = self.f(v)
    908         if isinstance(results[i], ABCSeries):
    909             # If we have a view on v, we need to make a copy because
    910             #  series_generator will swap out the underlying data
    911             results[i] = results[i].copy(deep=False)

Cell In[30], line 2, in <lambda>(column)
      1 tally = 0
----> 2 df.apply(lambda column: sum(isOne(column)), axis=1
      3         )

Cell In[29], line 2, in isOne(x)
      1 def isOne(x):
----> 2     if (x == 1):
      3         return 1 
      4     else:

File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\generic.py:1527, in NDFrame.__nonzero__(self)
   1525 @final
   1526 def __nonzero__(self) -> NoReturn:
-> 1527     raise ValueError(
   1528         f"The truth value of a {type(self).__name__} is ambiguous. "
   1529         "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1530     )

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

我试着在布尔表达式中附加.any(),.all()和.item,但是没有效果。

jdzmm42g

jdzmm42g1#

如果你想计算每一行中1的个数,可以使用矢量化代码,这样会快很多:

df.eq(1).sum(axis=1)

如果你想使用lambda作为练习:与axis=1一起使用时,x是包含该行值的Series。类似“series equal to 1?”的语句含义不明确。您的意思是该Series包含任意1还是全部1?请尝试以下操作:

def count_ones(x: pd.Series) -> int:
    return (x == 1).sum()

df.apply(count_ones, axis=1)
ecfsfe2w

ecfsfe2w2#

我不明白你的意思,是这个吗?

def isOne(arr):
    j = 0
    for i in arr:
        if (i == 1):
            j += 1
    return j

df.apply(isOne, axis=1)

相关问题