0

I'm trying to do a simple flag of 0/1

my data is

df = pd.dataframe({"id_gigya" :("A","B","C","D"), "material": ("FA","PE","AU","FA")})

My desired out put is

id_gigya   material   flag_fa
 A         FA        1
 B         PE        0
 C         AU        0
 D         FA        1

I used apply lambda and I get error.

df['flag_fa'] = df.apply(lambda x : 1 if df['material_group'] == 'FA' else 0)

my error is

The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index id_gigya'

Please let me know how do I solve this.

Thanks in advance

2 Answers2

3

You don't need apply here

df['flag_fa'] = df['material_group'].eq('FA').astype(int)

Or

df['flag_fa'] = np.where(df['material_group'].eq('FA'), 1, 0)

Or

df['flag_fa'] = df['material_group'].eq('FA').map({True : 1, False : 0})
ansev
  • 30,322
  • 5
  • 17
  • 31
2

When you apply a lambda function on a Series, you are applying the function to each element of the Series. So to correctly use apply, the syntax should be:

df['flag_fa'] = df["material"].apply(lambda x : 1 if x == 'FA' else 0)

But better is to use np.where.

Henry Yik
  • 22,275
  • 4
  • 18
  • 40