0

I am a beginner in python. I am trying to add a prefix to one of my columns in pandas if it meets a certain condition but i get the following error "ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()."

Below is my code

import pandas as pd
df = pd.DataFrame({'sk': [100, 234, 3333, 4569], 'lk': ['A', 'B', 'C', 'D']})

df['sk'] = df['sk'].astype(str)

length = df['sk'].apply(len)

    if length == 3:
        df['sk'] = 'CE0' + df['sk']
    else:
        df['sk'] = 'CE' + df['sk']
df
Duke
  • 13
  • 2
  • I strongly recommend reading the Pandas docs. This question is quite common, had you done any research whatsoever? – AMC Dec 23 '19 at 22:42
  • Does this answer your question? [Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()](https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o) – AMC Dec 23 '19 at 22:42

5 Answers5

1

Change your code to:

df['sk'] = df['sk'].apply(lambda txt: ('CE0' if len(txt) == 3 else 'CE') + txt)
Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
0

You can do:

import pandas as pd
df = pd.DataFrame({'sk': [100, 234, 3333, 4569], 'lk': ['A', 'B', 'C', 'D']})

df['sk'] = df['sk'].astype(str)

df['sk'] = df['sk'].apply(lambda x: f"CEO{x}" if len(x)==3 else f"CE{x}")

Output:

   sk      lk
0  CEO100  A
1  CEO234  B
2  CE3333  C
3  CE4569  D
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34
0

try this:

df['sk'] = df['sk'].apply(lambda x: 'CEO{}'.format(x) if len(x) == 3 else 'CE{}'.format(x))
S3DEV
  • 8,768
  • 3
  • 31
  • 42
acrobat
  • 812
  • 4
  • 7
0

Using np.where and Series.str.len:

df['sk'] = np.where(df['sk'].str.len().eq(3), 'CEO' + df['sk'], 'CE' + df['sk'])

       sk lk
0  CEO100  A
1  CEO234  B
2  CE3333  C
3  CE4569  D
Erfan
  • 40,971
  • 8
  • 66
  • 78
0

While I do agree Lambda is a neat way to reduce the amount lines used, it might be easier do it like this:

def val_check(x):
    if len(x) == 3:
        return "CE0" + x
    return "CE" + x

df['sk'] = df['sk'].astype(str).apply(val_check)

Especially when you will be doing more complicated comparisons in the future!

Thijmen
  • 374
  • 2
  • 14