Pandas check for substring of x in column if found add string to x

Viewed 221

My dataframe has a max of 2 variations of each string e.g if the string is 'USD' then sometimes another entry with 'LDUSD' is present also...the entries without 'LD' are always present.

I need to apply x[0:2]+'_'+x[2:] but ONLY if the column contains an exact match of x[2:].

It must be done this way to ensure the change only happens to the relevant entries, as there are also various items which include either 'LD' in their default name e.g ('EGLD','LDO','SLD') or include the current x string e.g.('TUSD','USDT').

df['Asset'] = df['Asset'].apply(lambda x: x[0:2]+'_'+x[2:] if x[2:] in df['Asset'] else x)

The part after...in...doesn't work, and I'm at a loss as to how to proceed next. How do I check if the column ['Asset'] holds an exact match of x[2:]?

Apologies for the title I didn't really know what to call this one...

EDIT a few examples out of circa 400:

df['Asset'] = ['1INCH','AAVE','ADA','ALGO','EGLD','DASH','LDO','TUSD','USDT','LD1INCH','LDALGO','LDEGLD','LDDASH','LDLDO','LDTUSD','LDUSDT',]

What I need:

df['Asset'] = ['1INCH','AAVE','ADA','ALGO','EGLD','DASH','LDO','TUSD','USDT','LD_1INCH','LD_ALGO','LD_EGLD','LD_DASH','LD_LDO','LD_TUSD','LD_USDT',]

2 Answers

You can use str.contains() to test if any() match rf'^{x[2:]}$':

df['Asset'] = df['Asset'].apply(lambda x: x[:2]+'_'+x[2:]
    if df['Asset'].str.contains(rf'^{x[2:]}$', regex=True).any() else x)

For regex, add r to make it a raw string. In this case we also add the f so we can interpolate x[2:] via f-string:

  • ^ - beginning of string
  • {x[2:]} - interpolate x[2:] inside the f-string
  • $ - end of string

Do you want something like this? If the end has 'USD' but contains more then give it an underscore before USD?

df = pd.DataFrame(columns=['Asset'], data=['1INCH','AAVE','ADA','ALGO','EGLD','DASH','LDO','TUSD','USDT','LD1INCH','LDALGO','LDEGLD','LDDASH','LDLDO','LDTUSD','LDUSDT',])
df['Asset'].apply(lambda x: x[:2]+'_'+x[2:] if len(x) > 2 and x[2:] in df['Asset'].values else x)
Related