- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有大量数据转换是用支持这种结构的批量转换语言定义的: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/
我正在尝试并行运行具有循环返回值的函数。但它似乎停留在 results = pool.map(algorithm_file.foo, population) 在 for 循环的第二次迭代中 r
Serving Flask 应用程序“服务器”(延迟加载) 环境:生产警告:这是一个开发服务器。不要在生产部署中使用它。请改用生产 WSGI 服务器。 Debug模式:开启 在 http://0.0.
我使用“product.pricelist”模型中的 get_product_price_rule() 函数。我的代码是: price = self._get_display_price(produ
我收到以下错误: Traceback (most recent call last): File "/home/odroid/trackAndFollow/getPositions.py", line
我正在尝试采用机器学习方法,但遇到了一些问题。这是我的代码: import sys import scipy import numpy import matplotlib import pandas
我尝试使用 tensorflow 1.4.0 对我的原始记录进行分类。过程如下。 拳头:读取图片和标签,输出“tfrecord”格式的文件。第二:读取tf记录和训练 编写tfrecord脚本是 !/u
我是新手,所以需要任何帮助,当我要求一个例子时,我的教授给我了这段代码,我希望有一个工作模型...... from numpy import loadtxt import numpy as np fr
我无法弄清楚为什么会出现此 ValueError...为了提供一些上下文,我正在使用 requests、BeautifulSoup 和 json 与 python 来抓取站点 json 数据。 我不确
我已经尝试使用这两个循环以及列表理解。即使我正在尝试将数字转换为列表中的整型,两者都无法解析整数。
我已经尝试使用这两个循环以及列表理解。即使我正在尝试将数字转换为列表中的整型,两者都无法解析整数。
我只有四个星期的 Python 经验。使用 Tkinter 创建一个工具,将新的公司 Logo 粘贴到现有图像之上。 下面的方法是获取给定目录中的所有图像并将新 Logo 粘贴到初始级别。现有图像、编
我只有四个星期的 Python 经验。使用 Tkinter 创建一个工具,将新的公司 Logo 粘贴到现有图像之上。 下面的方法是获取给定目录中的所有图像并将新 Logo 粘贴到初始级别。现有图像、编
我在尝试在 Keras 2.0.8、Python 3.6.1 和 Tensorflow 后端中训练模型时遇到问题。 错误消息: ValueError: Error when checking targ
我已经尝试使用这两个循环以及列表理解。即使我正在尝试将数字转换为列表中的整型,两者都无法解析整数。
我有这段代码: while True: try: start = int(input("Starting number: ")) fin = int(i
我是 python 的初学者编码员,试图制作一个“模具滚筒”,您可以在其中选择模具的大小,它在我的代码的第 20 行返回此错误 import sys import random import geto
我有以下代码: import fxcmpy import pandas as pd from pandas import datetime from pandas import DataFrame a
我正在尝试使用 django 和 python 制作一个博客应用程序。我也在尝试使用 s3 存储桶进行存储,使用 heroku 进行部署。我正在学习 coreymschafer 的在线教程。我正在按照
我创建了一个 numpy 数组(考虑输入数据)并想更改顺序(一些数值运算后的输出数据)。在使用转换后的数组时,我遇到错误并找到了根本原因。请在下面找到详细信息并使用 numpy 版本 1.19.1 i
我已经引用了之前的查询 All arguments should have the same length plotly但仍然没有得到我的问题的答案。 我有一个黄金价格数据集。 Date
我是一名优秀的程序员,十分优秀!