基于其他列的条件创建列

2024-06-16 11:38:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个“俱乐部”专栏,里面有英超俱乐部的名字,但是俱乐部的名字不适合我想要实现的目标。我试着用条件语句编写一个函数,以我想要的格式用俱乐部的名称填充另一列。我已尝试将我的函数应用于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 df

这是我的函数,名为:

#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和数据科学/分析。我会很感激一个解决方案,一个错误的解释和我做错了什么


Tags: 函数namecitydfreturn名字united俱乐部
1条回答
网友
1楼 · 发布于 2024-06-16 11:38:51

我认为通过熊猫的替换()可以更容易地实现这一点

只需创建一个旧值到新值的字典:

例如:

dict_replace = {
    'Tottenham Hotspur TOT':'Tottenham',
    'Liverpool LIV':'Liverpool',
    'Southampton SOU':'Southampton',
    'Chelsea CHE':'Chelsea'
    } #etc

然后使用字典更新数据框中的列:

假设要更改的df中的列名为club

df['club'].replace(dict_replace, inplace=True)

或者,如果您想要一个单独的列,而不是覆盖:

df['club_name_new'] = df['club'].replace(dict_replace)

完整测试示例:

import pandas as pd
df = pd.DataFrame({'club': ['Tottenham Hotspur TOT', 
                            'Liverpool LIV', 
                            'Southampton SOU', 
                            'Chelsea CHE', 
                            'Some other club'], 
                   'column': ['b', 'a', 'c', 'd', 'e'],'column2': [1, 2, 3, 4, 5]})
print('INITIAL DATAFRAME:')
print(df)
print('*'*10)

dict_replace = {
    'Tottenham Hotspur TOT':'Tottenham',
    'Liverpool LIV':'Liverpool',
    'Southampton SOU':'Southampton',
    'Chelsea CHE':'Chelsea'
    }

df['club_name_new'] = df['club'].replace(dict_replace)
print('DATAFRAME WITH NEW COLUMN NAMES:')
print(df)

将已处理的df返回为:

                    club column  column2    club_name_new
0  Tottenham Hotspur TOT      b        1        Tottenham
1          Liverpool LIV      a        2        Liverpool
2        Southampton SOU      c        3      Southampton
3            Chelsea CHE      d        4          Chelsea
4        Some other club      e        5  Some other club

后续意见:

使用规则应用更改的可能方式:

## replace 'United' with 'Utd':
df['club'].str.replace('United', 'Utd')

## remove last 4 characters:
df['club'].str[:-4]

然后为未遵循模式的剩余异常创建一个字典,并应用该字典

也就是说,对于从某个唯一值到另一个唯一值的特定转换,您必须制作一个字典(否则程序如何知道要更改为什么?)。但是,如果可以将更改简化为某种模式,则可以使用.str.replace()

相关问题 更多 >