带有 2 个元素超过 2 列的 for 循环的 ValueError _ pandas
ValueError with for loop with 2 elements over 2 cols _ pandas
我正在尝试为我的 df(命名为:controls)的 2 列中的每一行计算平均值+3*标准差,然后将值添加为新列。
我的代码是这样的:
for l, r in controls[['means1', 'std1']]:
controls['Threshold']=l+(3*r)
我收到这个错误:
ValueError: too many values to unpack (expected 2)
如果有任何建议或帮助,我将不胜感激!
谢谢,
S
您不需要循环。对于这样的计算,您可以一次乘以并添加整个列。
controls['Threshold'] = controls['means1'] + (3 * controls['std1'])
这将比逐行迭代更简单、更快,因为Pandas可以在numpy中完成整个操作。但是,如果您打算遍历行,请查看 iterrows.
如果可能,您不应该在 Pandas 中使用 for 循环。它很慢,因为它必须处理较慢的解释 Python 代码,而不是通过 Numpy 处理漂亮而快速的 C。您可以通过以下方式做到这一点:
controls['threshold'] = controls['means1'] + 3 * controls['std1']
controls.eval('threshold = means1 + 3 * std1', inplace=True)
我正在尝试为我的 df(命名为:controls)的 2 列中的每一行计算平均值+3*标准差,然后将值添加为新列。 我的代码是这样的:
for l, r in controls[['means1', 'std1']]:
controls['Threshold']=l+(3*r)
我收到这个错误:
ValueError: too many values to unpack (expected 2)
如果有任何建议或帮助,我将不胜感激!
谢谢, S
您不需要循环。对于这样的计算,您可以一次乘以并添加整个列。
controls['Threshold'] = controls['means1'] + (3 * controls['std1'])
这将比逐行迭代更简单、更快,因为Pandas可以在numpy中完成整个操作。但是,如果您打算遍历行,请查看 iterrows.
如果可能,您不应该在 Pandas 中使用 for 循环。它很慢,因为它必须处理较慢的解释 Python 代码,而不是通过 Numpy 处理漂亮而快速的 C。您可以通过以下方式做到这一点:
controls['threshold'] = controls['means1'] + 3 * controls['std1']
controls.eval('threshold = means1 + 3 * std1', inplace=True)