我有一个在 pandas 中运行的小函数,当我运行时会抛出 ValueErrorif x in y
陈述。我看到了类似的问题,建议使用布尔索引,.isin()
, and where()
,但我无法将任何示例适应我的情况。任何建议将非常感激。
附加说明:groups
是包含数据框外部字符串的列表的列表。我使用该函数的目标是查看数据框中的项目位于哪个列表,然后返回该列表的索引。我在下面的笔记本链接中使用的第一个版本iterrows
循环遍历数据帧,但我知道在大多数情况下这不是最佳的。
Jupyter 笔记本有一些虚假数据:https://github.com/amoebahlan61/sturdy-chainsaw/blob/master/Grouping%20Test_1.1.ipynb https://github.com/amoebahlan61/sturdy-chainsaw/blob/master/Grouping%20Test_1.1.ipynb
谢谢你!
Code:
def groupFinder(item):
for group in groups:
if item in group:
return groups.index(group)
df['groupID2'] = groupFinder(df['item'])
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-16-808ac3e51e1f> in <module>()
4 return groups.index(group)
5
----> 6 df['groupID2'] = groupFinder(df['item'])
<ipython-input-16-808ac3e51e1f> in groupFinder(item)
1 def groupFinder(item):
2 for group in groups:
----> 3 if item in group:
4 return groups.index(group)
5
~\AppData\Local\Continuum\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 Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Solution我遇到了一些 pandas 博客文章,也从 Reddit 用户那里得到了一些反馈,这给了我一个跳过使用的解决方案iterrows
通过使用 pandas'apply
功能。
df['groupID2'] = df.item.apply(groupFinder)
感谢大家的帮助和回复。