Home > OS >  How to add values from a list and a corresponding for loop to a dataframe
How to add values from a list and a corresponding for loop to a dataframe

Time:08-11

I have a list of variables as below:

variables = ['positional_versatility', 'weak_foot', 'skill_moves']

Then I have a for loop which prints the coefficient of each variable:

for (v, c) in zip(variables, model.coef_):
    print("%s has coefficient %5.4f" % (v, c))

Which outputs:

positional_versatility has coefficient 0.0041
weak_foot has coefficient -0.0421
skill_moves has coefficient 0.0010

My question: how do I add these coefficient values, with their corresponding variable names, to a dataframe?

CodePudding user response:

Use DataFrame constructor for 2 columns DataFrame:

df = pd.DataFrame({'a':variables, 'b': model.coef_})

CodePudding user response:

Use dict and zip with the DataFrame constructor:

df = pd.DataFrame([dict(zip(variables, model.coef_))])

output:

   positional_versatility  weak_foot  skill_moves
0                  0.0041    -0.0421        0.001

or better use a Series:

s = pd.Series(coef, index=variables)
# or
# s = pd.Series(dict(zip(variables, coef)))

output:

positional_versatility    0.0041
weak_foot                -0.0421
skill_moves               0.0010
dtype: float64
  • Related