我正在尝试迭代两个 python 数据帧列来确定特定值,然后将结果添加到新列中。下面的代码抛出以下错误:
raise ValueError('Length of values does not match length of ' 'index')"
我不知道为什么?
数据框:
TeamID todayorno
1 sw True
2 pr False
3 sw False
4 pr True
代码:
team = []
for row in results['TeamID']:
if row == "sw":
for r in results['todayorno']:
if r == True:
team.append('red')
else:
team.append('green')
else:
team.append('green')
results['newnew'] = team
最佳答案
您正在迭代数据帧两次,这表明您有 2 个 for
循环。您最终得到的结果有 10 项,而不是所需的 4 项。
不需要显式迭代。您可以使用 numpy.select 来应用指定条件的值。
import numpy as np
mask = results['TeamID'] == 'sw'
conditions = [~mask, mask & results['todayorno'], mask & ~results['todayorno']]
values = ['green', 'red', 'green']
results['newnew'] = np.select(conditions, values, 'green')
print(results)
TeamID todayorno newnew
1 sw True red
2 pr False green
3 sw False green
4 pr True green
关于python - 如何使用 python2.7 使用嵌套 for 循环迭代数据帧并附加到新的数据帧列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50864810/