Creating a list of composite names separated by underscore given a data frame

Viewed 50

We are given a data frame that may look like this (I am sorry I wasn't able to show the data frame given the code below):

    import pandas as pd   
    data = {'ID':['HA12','HA12','HA12','HA20', 'HA20' ], 'Age': [20, 20, 20, 25, 25], 'Gender': ['M','M','M','F','F'], 'Classes':['Maths', 'Biology', 'Chemistry', 'Maths', 'English' ]}   
    df = pd.DataFrame(data)   
    print(df)

I want to create a list out of the data frame that I will use to name the columns of another data frame. Each element of the list should be composed of names that I want to select and separated by an underscore. You may observe that entries in many columns of the above data frame are the same. Moreover, the age was not included in any of the composite names. More precisely, the list should look like this:

List = ['HA12_M_Maths','HA12_M_Biology','HA12_M_Chemistry','HA20_F_Maths','HA20_F_English']

I tried something but was unsuccessful in creating the list that I need.

I will appreciate any suggestion or code.

1 Answers

try:

out=(df['ID']+'_'+df['Gender']+'_'+df['Classes']).tolist()

OR

out=df[['ID','Gender','Classes']].agg('_'.join,1).tolist()

output of out:

['HA12_M_Maths', 'HA12_M_Biology', 'HA12_M_Chemistry', 'HA20_F_Maths', 'HA20_F_English']

Note: If needed a list of unique elements then just chain .unique() to any of these method....For example:

out=(df['ID']+'_'+df['Gender']+'_'+df['Classes']).unique().tolist()
#OR
out=df[['ID','Gender','Classes']].agg('_'.join,1).unique().tolist()
Related