Tonz
Tonz

Reputation: 187

For Loop and The truth value of a Series is ambiguous

Looked through the answers to similar queries here but still unsure. Code below produces:

     for i in range(len(df)):
            if df[0]['SubconPartNumber1'].str.isdigit() == False :
                df['SubconPartNumber1'] = df['SubconPartNumber1'].str.replace(',', '/', regex = True)
                df['SubconPartNumber1'] = df['SubconPartNumber1'].str.replace(r"\(.*\)-", '/', regex = True)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Upvotes: 2

Views: 165

Answers (2)

Rickey
Rickey

Reputation: 524

Replace this:

if df[0]['SubconPartNumber1'].str.isdigit() == False :

with this:

if df[0]['SubconPartNumber1'].str.isdigit().empty:

There are other methods besides empty, but I think this will get you what you want.

Upvotes: 0

jezrael
jezrael

Reputation: 862661

In pandas you can avoid loops if possible. Your solution should be replace by boolean mask with ~ for invert instead == False and passed to DataFrame.loc:

m = df['SubconPartNumber1'].str.isdigit()
df.loc[~m, 'SubconPartNumber1'] = df.loc[~m, 'SubconPartNumber1'].str.replace(',', '/', regex = True).str.replace(r"\(.*\)-", '/', regex = True)

But because numeric has only numbers I think mask is not necessary here, also regex should be join by | for or, regex=True is default parameter, so should be omitted:

df = pd.DataFrame({'SubconPartNumber1':['345','aaa,','(bbb)-ccc']})
print (df)
  SubconPartNumber1
0               345
1              aaa,
2         (bbb)-ccc

df['SubconPartNumber1'] = df['SubconPartNumber1'].str.replace(r",|\(.*\)-", '/')
print (df)
  SubconPartNumber1
0               345
1              aaa/
2              /ccc

Upvotes: 2

Related Questions