gpt4 book ai didi

Python:循环 pd.DataFrame 中的行时出现 'ValueError: can only convert an array of size 1 to a Python scalar'

转载 作者:行者123 更新时间:2023-12-01 09:12:54 24 4
gpt4 key购买 nike

我想循环遍历 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

该代码对于前几行工作正常。然而,我随后总是遇到相同行的错误,即使我看不到这些行与其他行有何不同。

  1. 如果我不按上面所示处理 ValueError,我会收到错误消息 ValueError: can only conversion an array of size 1 to a Python scalar for the first大约 250 行后的时间。
  2. 如果我确实如上所示处理 ValueError,我会捕获四个此类错误,每个错误处理 block 各有两个错误(否则代码可以正常工作),但代码会停止进一步更新在大约 18% 的行之后进行强度评级,并且不会抛出任何错误消息。

如果您能帮助我 (a) 了解导致错误的原因以及 (b) 如何处理它们,我将非常感激。

由于这是我在 StackOverflow 上发表的第一篇文章,因此我尚未完全了解该论坛的常见发帖做法。如果我的帖子有任何需要改进的地方,请告诉我。

非常感谢!

最佳答案

仅供引用,

如果将 .item 应用于 numpy 数组,您将收到类似的错误。

在这种情况下,您可以使用 .tolist() 来解决。

关于Python:循环 pd.DataFrame 中的行时出现 'ValueError: can only convert an array of size 1 to a Python scalar',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51500889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com