Creating column names from multiple lists using for loop

Stack Overflow Asked on January 1, 2022

Say I have multiple lists:

names1 = [name11, name12, etc]
names2 = [name21, name22, etc]
names3 = [name31, name32, etc]

How do I create a for loop that combines the components of the lists in order (‘name11name21name31’, ‘name11name21name32’ and so on)?

I want to use this to name columns as I add them to a data frame. I tried like this:

Results['{}' .format(model_names[j]) + '{}' .format(Data_names[i])] = proba.tolist()

I am trying to take some results that I obtain as an array and introduce them one by one in a data frame and giving the columns names as I go on. It is for a machine learning model I am trying to make.

This is the whole code, I am sure it is messy because I am a beginner.

    Train = [X_train_F, X_train_M, X_train_R, X_train_SM]
    Test = [X_test_F, X_test_M, X_test_R, X_test_SM]
    models_to_run = [knn, svc, forest, dtc]
    model_names = ['knn', 'svc' ,'forest', 'dtc']
    Data_names = ['F', 'M', 'R', 'SM']
    Results = pd.DataFrame()

for T, t in zip(Train, Test):
for j, model in enumerate(models_to_run):, y_train.values.ravel())
    proba = model.predict_proba(t)
    proba = pd.DataFrame(proba.max(axis=1))
    proba = proba.to_numpy()
    proba = proba.flatten()
    Results['{}' .format(model_names[j]) + '{}' .format(Data_names[i])] = proba.tolist()

I dont know how to integrate ‘i’ in the loop, to use it to go through the list Data_names to add it to the column name. I am sure there is a cleaner way to do this. Please be gentle.

Edit: It currently gives me a data frame with 4 columns instead of 16 as it should, and it just adds the whole Data_names list to the column name.

One Answer

How about: Results= {}

for T, t, dname in zip(Train, Test, Data_names):

for mname, model in zip(model_names, models_to_run):


Results[(dname, mname)] = proba.to_list()

Results = pd.DataFrame(Results.values(), index=Results.keys()).T

Answered by RichieV on January 1, 2022

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP