fred.schwartz
fred.schwartz

Reputation: 2155

looping through dictionary and applying dataframe transformation

I have a dataframe. I want to say for all columns that start with 'A' or 'C', then divide all rows by the column average.

I can't see why my code isn't working.

   dict_trans={'A':'STA'
    ,'B':'SUB'
    ,'C':'STA'}




for k, v in dict_trans.items():
    if df_train.columns.str.startswith(k):
        transformation=v
        if transformation='STA':
            df['STA_'+varname]=df[varname]/df.groupby(level=1)[varname].transform('mean')

Upvotes: 0

Views: 380

Answers (1)

vrana95
vrana95

Reputation: 521

Please follow the code below. I hope you are trying to do the operations on certain columns starting with certain matched character and wanted to create new feature from that.

   # Creating a sample data frame : 
df=pd.DataFrame({'A_1':range(10),
         'A_2':range(10,20),
          'B_2':range(21,31),
         'C_1':range(32,42)})


columns_required=list(filter(lambda x:(x.startswith('A') or x.startswith('C') ),(df.columns).tolist()))

dict_trans={'A_1':'STA'
    ,'A_2':'SUB'
    ,'B_2':'STA',
     'C_1':'STA'}

for index,value in dict_trans.items():
    if index in columns_required and value=='STA':
        df['STA_'+index]=df.loc[:,index]/(df.loc[:,index]).mean()

Outcome is :

   A_1  A_2 B_2 C_1  STA_A_1        STA_C_1
0   0   10  21  32  0.000000    0.876712
1   1   11  22  33  0.222222    0.904110
2   2   12  23  34  0.444444    0.931507
3   3   13  24  35  0.666667    0.958904
4   4   14  25  36  0.888889    0.986301
5   5   15  26  37  1.111111    1.013699
6   6   16  27  38  1.333333    1.041096
7   7   17  28  39  1.555556    1.068493
8   8   18  29  40  1.777778    1.095890
9   9   19  30  41  2.000000    1.123288

Code snippet

Upvotes: 1

Related Questions