1

Im trying to replace the column names of a dataframe (sens_second_X) based on the strings in a list (updated_fist_stage) being substrings to the column names. updated_fist_stage = ['ccc_230', 'LN_S_P500', 'mf_100'] and

sens_second_X.columns = ['resid', 'ccc_230_TY',
       EQ_ETF', 
       'LN_S_P500_changes', 'mf_100_equity', 'inflows_2009',
        'inflows_2010']

I try to do this as follows:

def renaming_fun(x):
    for var in updated_fist_stage: 
        if var in x:
            return var
        return x
sens_second_X.columns = map(renaming_fun, sens_second_X.columns)

but I get that only ccc_230 has been renamed in the dataframe and the output is as follows:

sens_second_X.columns = ['resid', 'ccc_230',
       EQ_ETF', 
       'LN_S_P500_changes', 'mf_100_equity', 'inflows_2009',
        'inflows_2010']

2 Answers 2

1

You can try something like below with str.extract

mapped = sens_second_X.columns.str.extract(r'({})'.format('|'.join(updated_fist_stage))
                                                        ,expand=False)
sens_second_X.columns = pd.Index(pd.Series(mapped).fillna(pd.Series(sens_second_X.columns)))

Index(['resid', 'ccc_230', 'EQ_ETF', 'LN_S_P500', 'mf_100', 'inflows_2009',
   'inflows_2010'],
  dtype='object')
Sign up to request clarification or add additional context in comments.

Comments

1

Your return x was just at the wrong indent :

def renaming_fun(x):
    for var in updated_fist_stage: 
        if var in x:
            return var
    return x  # <---- HERE IS THE CHANGE
sens_second_X.columns = map(renaming_fun, sens_second_X.columns)

What happened to you before : the if condition was verified for ccc_230, it returned var, and then it returned x for the rest of the iterator. So the function renaming_fun() was only called once

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.