![](/img/trans.png)
[英]Python error: ValueError: can only convert an array of size 1 to a Python scalar
[英]Python: 'ValueError: can only convert an array of size 1 to a Python scalar' when looping over rows in pd.DataFrame
我想遍历 DataFrame 的行,在我的例子中计算多个运动队的强度等级。
DataFrame 列'home_elo'
和'away_elo'
包含所涉及球队的赛前实力评级(ELO 分数),并在比赛结束后在下一场主/客场比赛的行中更新(每支球队在任何时候都有两个实力评级)时间点,对于主客场比赛),以及update_elo(a,b,c)
返回的内容。
相应的代码片段如下所示:
for index in df.index:
counter = counter + 1
# Calculation of post-match ELO scores for home and away teams
if df.at[index,'updated'] == 2: # Update next match ELO scores if not yet updated but pre-match ELO scores available
try:
all_home_fixtures = df.date_rank[df['localteam_id'] == df.at[index,'localteam_id']]
next_home_fixture = all_home_fixtures[all_home_fixtures > df.at[index,'date_rank']].min()
next_home_index = df[(df['date_rank'] == next_home_fixture) & (df['localteam_id'] == df.at[index,'localteam_id'])].index.item()
except ValueError:
print('ERROR 1 at' + str(index))
df.at[index,'updated'] = 4
try:
all_away_fixtures = df.date_rank[df['visitorteam_id'] == df.at[index,'visitorteam_id']]
next_away_fixture = all_away_fixtures[all_away_fixtures > df.at[index,'date_rank']].min()
next_away_index = df[(df['date_rank'] == next_away_fixture) & (df['visitorteam_id'] == df.at[index,'visitorteam_id'])].index.item()
except ValueError:
print('ERROR 2 at' + str(index))
df.at[index,'updated'] = 4
# print('Current: ' + str(df.at[index,'fixture_id']) + '; Followed by: ' + str(next_home_fixture))
# print('Current date rank: ' + str(df.at[index,'date']) + ' ' + str(df.at[index,'date_rank']) + '; Next home date rank: ' + str(df.at[next_home_index,'date_rank']) + '; Next away date rank: ' + str(df.at[next_away_index,'date_rank']))
df.at[next_home_index, 'home_elo'] = update_elo(df.at[index,'home_elo'],df.at[index,'away_elo'],df.at[index,'actual_score'])
df.at[next_away_index, 'away_elo'] = update_elo(df.at[index,'away_elo'],df.at[index,'home_elo'],1 - df.at[index,'actual_score']) # Swap function inputs for away team
df.at[next_home_index, 'updated'] = df.at[next_home_index, 'updated'] + 1
df.at[next_away_index, 'updated'] = df.at[next_away_index, 'updated'] + 1
df.at[index,'updated'] = 3
该代码适用于前几行。 然而,我遇到错误,总是针对相同的行,即使我看不出这些行与其他行有何不同。
ValueError
,我会收到错误消息ValueError: can only convert an array of size 1 to a Python scalar
for the first time after about 250 rows.ValueError
,我会捕获四个这样的错误,每个错误处理块有两个(否则代码工作正常),但代码在所有行的大约 18% 之后停止更新任何进一步的强度评级,不抛出任何错误信息。如果您能帮助我 (a) 了解导致错误的原因以及 (b) 如何处理它们,我将不胜感激。
由于这是我在 StackOverflow 上的第一篇文章,我还没有完全了解论坛的常见发帖习惯。 如果我的帖子有什么可以改进的地方,请告诉我。
非常感谢!
供参考,
如果您将.item
应用于 numpy 数组,您将收到类似的错误。
在这种情况下,您可以使用.tolist()
解决它。
pd.Series.item
需要系列中至少有一项才能返回标量。 如果:
df[(df['date_rank'] == next_home_fixture) & (df['localteam_id'] == df.at[index,'localteam_id'])]
是一个长度为 0 的系列,那么.index.item()
将抛出一个 ValueError。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.