Search code examples
pandasloopsassign

Create a new variable for every row in dataframe column


I'm trying to create a series of variables based on an existing df column. Example :

import pandas as pd

dates = {'expiries': ['10','11','13','14']}
expiries = pd.DataFrame(dates)
expiries 

I then want to create a new variable (var1 through var4) giving it the value from each row. I know I can get it by going:

var1 = expiries['expiries'].iloc[0]
var2 = expiries['expiries'].iloc[1]
var3 = expiries['expiries'].iloc[2]
var4 = expiries['expiries'].iloc[3]

but in reality my df is a variable length and I need a variable per row not a pre determined (hardcoded) number of variables.


Solution

  • store them in the dict:

    var_dict = {}
    for i in range(expires.shape[0]):
        var_dict['var' + str(i+1)] = expiries['expiries'].iloc[i]
    

    it is against coding logic that you have unknown number of variables