-1

I am trying to change the strings in a Pandas Series by a condition. If the string name is say 'A', it should be 'AA'. The code snippet below works but it is very un elegant and inefficient. I am passing a Pandas series as an argument as I said. Is there any other way to accomplish this?


def conditions(x):
    if x == 'A':
        return "AA"
    elif x == 'B':
        return "BB"
    elif x == 'C':
        return "CC"
    elif x == 'D':
        return "DD"
    elif x == 'E':
        return "EE"
    elif x == 'F':
        return "FF"
    elif x == 'G':
        return "GG"
    elif x == 'H':
        return "HH"
    elif x == 'I':
        return "I"
    elif x == 'J':
        return "JJ"
    elif x == 'K':
        return "KK"
    elif x == 'L':
        return 'LL'

func = np.vectorize(conditions)
test = func(rfqs["client"])

3 Answers 3

2

If you are just trying to repeat a given string, you can add the string to itself across all rows at once. If you have some other condition, you can specify that condition and add the string to itself only for rows that meet the criteria. See this toy example:

df = pd.DataFrame({'client': ['A', 'B', 'Z']})

df.loc[df['client'].str.contains('[A-L]'), 'client'] = df['client'] * 2

to get

  client
0     AA
1     BB
2      Z
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a dictionary to avoid all those if elses:

d = {i:2*i for i in ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L')} 

test = rfqs["client"].apply(lambda x: d[x] if x in d else x)

Comments

1

Here is another way:

l = list('ABCDEFGHIJKL')
df['col'] = df['col'].mask(df['col'].isin(l),df['col'].str.repeat(2))

With np.where()

df['col'].mul(np.where(df['col'].isin(l),2,1))

With map()

df['A'].mul(df['A'].map({i:2 for i in l}).fillna(1).astype(int))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.