gpt4 book ai didi

python - 在 Dataframe.assign() 中使用 if/else 导致 ValueError : The truth value of a Series

转载 作者:太空宇宙 更新时间:2023-11-04 09:31:56 24 4
gpt4 key购买 nike

我有大量数据转换是用支持这种结构的批量转换语言定义的:x = iif(condition, a, b)。我想使用数据框重写这些。

我正在使用 Dataframe.assign() 但得到 ValueError: The truth value of a Series is ambiguous。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

    import pandas as pd
df = pd.DataFrame(['apple', 'orange', 'granite'], columns=['name'])
df.assign(taste = lambda x: 'rocky' if (x.name=='granite') else 'yummy')

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-39-e9ad71ccc45b> in <module>()
----> 1 df.assign(taste = lambda x: 'rocky' if (x.name=='granite') else 'yummy')

~\Anaconda3\lib\site-packages\pandas\core\frame.py in assign(self, **kwargs)
3305 if PY36:
3306 for k, v in kwargs.items():
-> 3307 data[k] = com._apply_if_callable(v, data)
3308 else:
3309 # <= 3.5: do all calculations first...

~\Anaconda3\lib\site-packages\pandas\core\common.py in _apply_if_callable(maybe_callable, obj, **kwargs)
403
404 if callable(maybe_callable):
--> 405 return maybe_callable(obj, **kwargs)
406
407 return maybe_callable

<ipython-input-39-e9ad71ccc45b> in <lambda>(x)
----> 1 df.assign(taste = lambda x: 'rocky' if (x.name=='granite') else 'yummy')

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

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

起初我认为这是由于 assign() 中允许的关键字的限制,但一个非常相似的结构适用于 apply():

df['name'].apply(lambda x: 'rocky' if (x=='granite') else 'yummy')

0 yummy
1 yummy
2 rocky
Name: name, dtype: object

但是,这不允许我使用使用数据框中多列的 if 条件。有没有办法让 assign() 工作?

最佳答案

调用 Series.apply 时,lambda 会接收每一行值(即标量值)。使用 assign,lambda 接收整个 DataFrame。理解这一点意味着您现在可以做一些事情,例如

df.assign(taste=lambda x: np.where(x['name'] == 'granite', 'r', 'y'))

name taste
0 apple y
1 orange y
2 granite r

或者,

df.assign(taste=np.where(df['name'] == 'granite', 'r', 'y'))
name taste
0 apple y
1 orange y
2 granite r

或者,更简单地说,对于就地赋值,

df['taste'] = np.where(df['name'] == 'granite', 'r', 'y')
df

name taste
0 apple y
1 orange y
2 granite r

关于python - 在 Dataframe.assign() 中使用 if/else 导致 ValueError : The truth value of a Series,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55407474/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com