2

I wish to create a dictionary of dataframes so I can pass into a function. Each dataframe is just a single line string.

Input:

test1=['1','2']
dn=['x','y']
Mag =['tet1','tet2']
pm=['1','2'] 

keys=[]
final_list=[]
df = pd.DataFrame()

for num1 in test1:
    for num2 in dn:
        for num3 in Mag:
            for num4 in pm:
                keys.append(f'sw{num4}O{num1}{num2}{num3}')
                final_list.append(f'mp{num4}-ghfg{num1}-{num2}-{num3}')
                df=pd.DataFrame(final_list)
                df.append(df)

d = {}
d= dict(zip(keys, df))

Output:

In d['sw1O1xtet1']

Out 0

Desired Output: a dataframe containing the single line string 'mp1-ghfg1-x-tet1' corresponding to its key... NOt sure how to fix this...

2
  • 1
    You define df as a [] and next you use it as DataFrame - why? Commented Oct 5, 2020 at 9:50
  • my mistake as a beginner. I have changed it to df = pd.DataFrame(). Still investigating. Commented Oct 5, 2020 at 10:04

3 Answers 3

2

You can put each value in a dataframe before adding it to the dictionary. And you don't need the intermediate lists if you construct the dictionary directly by adding key-value pairs:

test1 = ['1', '2']
dn = ['x', 'y']
Mag = ['tet1', 'tet2']
pm = ['1', '2'] 

d = {}

for num1 in test1:
    for num2 in dn:
        for num3 in Mag:
            for num4 in pm:
                key = f'sw{num4}O{num1}{num2}{num3}'
                value = pd.DataFrame({'col1': [f'mp{num4}-ghfg{num1}-{num2}-{num3}']})
                d[key] = value
Sign up to request clarification or add additional context in comments.

1 Comment

exactly what i needed.. to avoid creating a list. thanks!
1

The following code snippet will provide you the desired output.

import pandas as pd
test1=['1','2']
dn=['x','y']
Mag =['tet1','tet2']
pm=['1','2'] 

keys=[]
final_list=[]

for num1 in test1:
    for num2 in dn:
        for num3 in Mag:
            for num4 in pm:
                keys.append(f'sw{num4}O{num1}{num2}{num3}')
                final_list.append(f'mp{num4}-ghfg{num1}-{num2}-{num3}')

d = {}
d = dict(zip(keys, final_list))

print(d['sw1O1xtet1'])

1 Comment

Thanks for your suggestion but unfortunately the constraint is that the output has to be a dafaframe containing this single line string
1

In order to understand what's wrong with your code, you can have a look at the result of zip

>>> [(a,b) for (a,b) in zip(keys, df)]
[('sw1O1xtet1', 0)]

So you should not pass the whole dataframe to zip, only the first column df[0]

Also pay attention to the indentation, as the last 2 lines in the loop should be after the loop, not inside

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.