Convert mixed of flat index and simple index to simple column names

Viewed 20

I am trying to convert mixed of simple index and flat index to simple column names

index = pd.Index([                 'id',
                                'gender',
                                   'age',
                      ('var', 'mask', 3),
                      ('var', 'mask', 4),
                      ('var', 'mask', 1),])

expected:

index = ['id', 'gender', 'age', 'var_mask_3', 'var_mask_4', 'var_mask_1']

I try [ '_'.join(str(x)) for x in index ]but got :

'i_d',
 'g_e_n_d_e_r',
 'a_g_e',
 "(_'_v_a_r_'_,_ _'_m_a_s_k_'_,_ _3_)",
 "(_'_v_a_r_'_,_ _'_m_a_s_k_'_,_ _4_)",
 "(_'_v_a_r_'_,_ _'_m_e_a_n_'_,_ _1_)"]

and if it try [ '_'.join(x) for x in index ], I got the error TypeError: sequence item 2: expected str instance, int found

1 Answers

You can use a conditional map:

index.map(lambda t: '_'.join(str(x) for x in t) if isinstance(t, tuple) else t)

Or as a list comprehension:

['_'.join(str(x) for x in t) if isinstance(t, tuple) else t for t in index]

output:

Index(['_id', 'gender', 'age', 'var_mask_3', 'var_mask_4', 'var_mask_1'],
      dtype='object')
Related