【问题标题】:Creating a pandas column based on conditions from another column根据另一列的条件创建 pandas 列
【发布时间】: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


【解决方案1】:

我认为这可以通过 panda 的 replace() 更轻松地实现。

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

例如:

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()

【讨论】:

  • 我试过了,但它只是创建了新的 'club_name_new' 列,其中的行与 'Club' 列中的行相同。这些行未按预期包含字典值。
  • 您的字典中的值是否与列中的值完全匹配?它只替换匹配的地方
  • 我添加了一个全文示例。仔细检查您是否引用了正确的字典,并且字典中的名称是否与您正在查找的名称匹配(空格、大写等)
  • 非常感谢@yulGM。终于弄清楚了为什么这个和我之前的功能不起作用。正如您所怀疑的那样,这是空间的问题。有没有一种更简单的方法来浏览我想要替换的列,而不必像我一样手动输入所有行或创建字典?也许使用循环?
  • 这是一个不同的问题 :) 并且在不知道您的数据、列等的情况下很难分辨。但基本上您会使用字典来执行从一个值到另一个值的特定替换。但除此之外,关于是什么促使你改变价值观,也许有规则/逻辑?例如:'删除最后 4 个字符'。将“United”替换为“Utd”。您可以执行类似的操作,然后应用字典更改来更改未解决的异常。我将添加这两个示例来回答,以便您开始。在 pd.str.replace() 等上阅读熊猫。
猜你喜欢
  • 1970-01-01
  • 2022-10-15
  • 1970-01-01
  • 2020-04-16
  • 1970-01-01
  • 2021-06-11
  • 1970-01-01
  • 1970-01-01
  • 2018-11-27
相关资源
最近更新 更多