0

I am looping through elements of lists that vary in length and content. Here is the object (keys) that I use:

keys:
key   dims                         
1     ['site', 'channel', 'fiscal_week']
2     ['site', 'dude', 'other', 'fiscal_week']         
3     ['site', 'eng', 'dude', 'something_else', 'fiscal_week']    

I have a for loop where I loop through keys['dims']:

for key in keys['dims']:
    get desired output (see below)

I would like for this loop to output variables that I can use to identify columns in a pandas dataframe. For example, for key = 1, I would like to have this completed during the loop:

D1 = 'site'
D2 = 'channel'
D3 = 'fiscal_week'

When I get to key = 2, I will need to overwrite these variables, yielding:

D1 = 'site'
D2 = 'dude'
D3 = 'other'
D4 = 'fiscal_week'

My ultimate goal is to then use these variables like this:

df[D1]+df[D2]...

Here is my failed attempt:

for key in keys['dims']:
    print key
    d = {}
    i = 1
    for dim in key:
        d['D{0}'.format(i)]=dim
        print d        
        i +=1

This didn't work because it ended up giving this output:

['site', 'channel', 'fiscal_week']
{'D1': 'site'}
{'D2': 'channel', 'D1': 'site'}
{'D2': 'channel', 'D3': 'fiscal_week', 'D1': 'site'}
['site', 'dude', 'other', 'fiscal_week']
...etc.

Any help is much appreciated.

NLR
  • 1,714
  • 2
  • 11
  • 21

1 Answers1

1

IIUC

df=pd.DataFrame(data=yourdf.dims.values.tolist(),index=yourdf.key)
df.columns+=1
df=df.add_prefix('D')

df['D1']
Out[537]: 
key
1    site
2    site
3    site
Name: D1, dtype: object

df
Out[538]: 
       D1       D2           D3              D4           D5
key                                                         
1    site  channel  fiscal_week            None         None
2    site     dude        other     fiscal_week         None
3    site      eng         dude  something_else  fiscal_week

If you want it to be dictionary

d = df.to_dict('index')
BENY
  • 317,841
  • 20
  • 164
  • 234