0

I have this dataframe:

df = pd.DataFrame({'Player': ['Pele', 'Platini', 'Beckenbauer'],
                    'Position': ['Forward', 'Midfielder', 'Defender']})

And I have this function I need to apply to the dataframe, creating a new column 'color'.

def color(position):
    if position == 'Forward':
        color = 'black'
    elif position == 'Midfielder':
        color = 'white'
    elif position == 'Defender':
        color = 'red'

    return color

I have tried:

df['Color'] = df.apply(color, axis=1)

But I get the error:

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

How do I do this?

8-Bit Borges
  • 9,643
  • 29
  • 101
  • 198
  • you are passing all the column values. So you need to specifywhich column value you are referring to. – Pygirl Jul 26 '20 at 03:55
  • Take a look at this: https://stackoverflow.com/questions/51388201/fastest-way-to-create-a-pandas-column-conditionally – Pygirl Jul 26 '20 at 04:09

2 Answers2

3

You can use pd.Series.map here. Create a mapping dictionary and feed it to pd.Series.map

mapping = {'Forward':'black', 'Midfielder':'white', 'Defender':'red'}
df['Color'] = df['Position'].map(mapping)

        Player    Position  Color
0         Pele     Forward  black
1      Platini  Midfielder  white
2  Beckenbauer    Defender    red
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
0

It should be:

df['color'] = df['Position'].apply(color)

Or

def color(position):
    pos = position['Position']
    if pos == 'Forward':
        color = 'black'
    elif pos == 'Midfielder':
        color = 'white'
    elif pos == 'Defender':
        color = 'red'

    return color

df['color'] = df.apply(color, axis=1)

    Player      Position    color
0   Pele        Forward     black
1   Platini     Midfielder  white
2   Beckenbauer Defender    red
Pygirl
  • 12,969
  • 5
  • 30
  • 43