python - 使用 zip 形成新的数据框,但出现错误

标签 python python-2.7 pandas

我有一个名为 playoff_teams 的 numpy_array:

playoff_teams = np.sort(playoff_seeds['team'])
playoff_teams[:7]

array([1115, 1124, 1139, 1140, 1143, 1155, 1165], dtype=int64)

我有一个名为 reg 的 data_frame:

       season daynum    wteam   wscore  lteam   lscore  wloc    numot
108122  2010    7       1143     75      1293    70       H     0
108123  2010    7       1314     88      1198    72       H     0
108124  2010    7       1326     100     1108    60       H     0
108125  2010    7       1393     75      1107    43       H     0
108126  2010    9       1143     95      1178    61       H     0

然后我遍历团队并执行以下操作:

for teams in  playoff_teams:
    games = reg[(reg['wteam'] == teams) | (reg['lteam']== teams)]
    last_six = sum(games.tail(6)['wteam'] == teams)
    zipped = zip(team, last_six)

我得到一个错误

TypeError: zip argument #1 must support iteration

我需要按照以下格式形成一个新的数据框:

col_1   col_2
team_1   last_six
team_2   last_six
team_3   last_six

我该怎么做?

最佳答案

sum()返回一个数字,而不是你可以在 zip() 时迭代的东西需要迭代,所以我认为你的问题就在那里。

last_six = sum(games.tail(6)['wteam'] == teams)  # Number
zipped = zip(team, last_six)  # Error because last_six is not iterable

例如,您可以将结果存储在列表中(也可能是字典):

new_data = []
for teams in  playoff_teams:
    games = reg[(reg['wteam'] == teams) | (reg['lteam']== teams)]
    last_six = sum(games.tail(6)['wteam'] == teams)
    new_data.append((teams, last_six))

然后使用 DataFrame.from_itemsDataFrame.from_dict 构建您的数据框(如果您选择的是字典而不是列表)。

关于python - 使用 zip 形成新的数据框,但出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28942577/

相关文章:

python - 使用 itemgetter 对元组进行排序的困难

python - 在Python数据框中添加密集排名,其中所有列都在字符串中

Python:只保留最后n个插入键的字典

Python3 shebang 行未按预期工作

Python request.get 图片 - 太长 - 性能不佳

python - 在 pandas 数据框中将日期转换为日期时间格式时出现问题

python - 我想要这个列表理解的变体

python - 从具有相同文件名的两个列表中压缩项目?

python - 如何在Python中删除csv行中的重复单词?

python - 在Python中获取括号内的字符串