Apply and Lambda function - ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

Viewed 600

I'm trying to create a new column dividing 'ID' values by 219 if 'Gender' is 'Female and 393 if 'Gender is 'Male' by using Apply and Lambda functions. First, I tried to use 'Gender' column which has categorical variables which didn't work. so I created a binary column based on 'Gender' assigning 0 to 'Female 1 to 'Male' and use that column, but didn't work.

I'm still getting the value error like this:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

my code is

by_label_out_degree[NormID] = by_label_out_degree.apply(lambda row: row['ID']/ 219 if row['Gender2'] == 0 else row['ID']/ 393,axis=1)

I'm adding my code again! Thank you for your help!!

values = [
[42785,428855,'Energy','Female'],
[43432,428686,'Trust','Male'],
[43432,428686,'Career','Male'],
[43432,428686,'Personal','Male'],
[43432,428634,'Trust','Female']
]
df: pd.DataFrame = pd.DataFrame(values, columns =['ID','Target','Label','Gender'])
new_df = df.groupby(['Gender','Label']).ID.count().reset_index()
new_df['Gender2'] = new_df.Gender.map({'Female':0,'Male':1})
new_df['NormID'] = new_df.apply(lambda row: row['ID']/219 if row['Gender2'] == 0 else row['ID']/393, axis = 1)
1 Answers

Fix

The use of column Gender works nice

values = [
    ['Female', 'Access', 96],
    ['Female', 'Career', 165],
    ['Male', 'Access', 236],
    ['Male', 'Energy', 445]
]
df: pd.DataFrame = pd.DataFrame(values, columns=['Gender', 'Label', 'ID'])
df['newcol'] = df.apply(lambda row: row['ID'] / 219 if row['Gender'] == 'Female' else row['ID'] / 393, axis=1)
print(df)

   Gender   Label   ID    newcol
0  Female  Access   96  0.438356
1  Female  Career  165  0.753425
2    Male  Access  236  0.600509
3    Male  Energy  445  1.132316

Better

Use numpy.where

import numpy as np
import pandas as pd

values = [['Female', 'Access', 96], ['Female', 'Career', 165],
          ['Male', 'Access', 236], ['Male', 'Energy', 445]]
df: pd.DataFrame = pd.DataFrame(values, columns=['Gender', 'Label', 'ID'])
df['newcol'] = np.where(df['Gender'] == 'Female', df['ID'] / 219, df['ID'] / 393)
print(df)
Related