【发布时间】:2021-03-02 07:04:22
【问题描述】:
我的 pandas df 中有这个“俱乐部”列,其中包含英超联赛俱乐部的名称,但俱乐部的命名不适合我想要实现的目标。我尝试编写一个带有条件语句的函数,以我想要的格式用俱乐部名称填充另一列。我尝试将我的函数应用到我的 df 但我收到此错误:
ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index 0')
这就是 df 称为 test 的样子: test df
这是我的名为 clubs_name 的函数:
#We want to rename the clubs to be exact names like in Squad column in the epl_table_df dataframe
def clubs_name(Club):
if Club == 'Leicester City LEI':
return 'Leicester City'
elif Club == 'Tottenham Hotspur TOT':
return 'Tottenham'
elif Club == 'Liverpool LIV':
return 'Liverpool'
elif Club == 'Southampton SOU':
return 'Southampton'
elif Club == 'Chelsea CHE':
return 'Chelsea'
elif Club == 'Aston Villa AVL':
return 'Aston Villa'
elif Club == 'Everton EVE':
return 'Everton'
elif Club == 'Crystal Palace CRY':
return 'Crystal Palace'
elif Club == 'Wolverhampton Wanderers WOL':
return 'Wolves'
elif Club == 'Manchester City MCI':
return 'Manchester City'
elif Club == 'Arsenal ARS':
return 'Arsenal'
elif Club == 'West Ham United WHU':
return 'West Ham'
elif Club == 'Newcastle United NEW ':
return 'Newcastle Utd'
elif Club == 'Manchester United MUN':
return 'Manchester Utd'
elif Club == 'Leeds United LEE':
return 'Leeds United'
elif Club == 'Brighton and Hove Albion BHA':
return 'Brighton'
elif Club == 'Fulham FUL':
return 'Fulham'
elif Club == 'West Bromwich Albion WBA':
return 'West Brom'
elif Club == 'Burnley BUR':
return 'Burnley'
elif Club == 'Sheffield United SHU':
return 'Sheffield Utd'
else:
return Club'
当我测试我的功能时,它似乎正在工作:
print(clubs_name('Fulham FUL'))
这就是我尝试将该函数应用于测试 df 的方式:
test.apply (lambda Club: clubs_name(Club), axis=1)
我是 python 和数据科学/分析的新手。我会很感激一个解决方案,对错误的解释以及我做错了什么。
【问题讨论】:
-
您没有提供可重复的数据样本,因此很难对其进行测试(请参阅 How to make good pandas examples ),但是
test["Club"].apply(clubs_name) -
正如@G.Anderson 所说,我相信
test["Club"].apply(clubs_name)应该可以工作。 -
谢谢,我试过了,但没用。它只是给了我仍然是旧格式的数据的俱乐部列。我已附上 csv 文件的链接。 link
-
谢谢。我想出了问题所在。我的条件语句中的 Club 值比我的 df 中的 Club 列中的空格少。
标签: python pandas dataframe data-science data-analysis