python - 如何使用 python2.7 使用嵌套 for 循环迭代数据帧并附加到新的数据帧列?

标签 python python-2.7 pandas dataframe

我正在尝试迭代两个 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/

相关文章:

python - Groupby 多索引 AND 获取第一个索引的总和

python - 同一图中的正常和 cartopy 子图的组合

python - 属性错误 : 'datetime' module has no attribute 'strptime'

django - 使用 Django ORM 连接两个表之间的记录

python - 在 Pandas 条形图中设置 xticks

Python套接字接收 - 传入的数据包总是有不同的大小

python - sr*() 方法不在 scapy 中剖析回答的数据包

windows - python TypeError : must be encoded string without NULL bytes, 不是 str

python - 无法在 Jupyter Notebook 中使用 pyodbc 模块

python-2.7 - KeyError:不在索引中,使用从 Pandas 数据帧本身生成的键