Python 使用zip生成新数据帧,但出现错误
我有一个称为季后赛球队的numpy阵列:Python 使用zip生成新数据帧,但出现错误,python,python-2.7,pandas,Python,Python 2.7,Pandas,我有一个称为季后赛球队的numpy阵列: playoff_teams = np.sort(playoff_seeds['team']) playoff_teams[:7] array([1115, 1124, 1139, 1140, 1143, 1155, 1165], dtype=int64) 我有一个名为reg的数据帧: season daynum wteam wscore lteam lscore wloc numot 108122 2010
playoff_teams = np.sort(playoff_seeds['team'])
playoff_teams[:7]
array([1115, 1124, 1139, 1140, 1143, 1155, 1165], dtype=int64)
我有一个名为reg
的数据帧:
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
我该怎么做?返回一个数字,而不是在需要可重用时可以迭代的数字,所以我认为您的问题就在这里
last_six = sum(games.tail(6)['wteam'] == teams) # Number
zipped = zip(team, last_six) # Error because last_six is not iterable
您可以将结果存储在列表中(也可以是dict),例如:
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\u items
或DataFrame.from\u dict
(如果您选择的是dict而不是列表)构建您的数据框。是的,我使用了itertools。对zip的两个参数重复,但我的ipython笔记本被击中。我认为这个操作有点昂贵为什么不返回一个简单的元组,比如(团队,最后六个)
?使用元组我会得到这样一个o/p:(1115,5)(1124,5)
,但是我如何从中形成一个数据帧呢?我编辑了我的答案。您可以使用DataFrame.from\u items
功能。我得到了它。我不知道为什么删除了另一个解决方案?