0

I have two data frames.

DF1

col1           col2
price($)       price(#)    
dimension(m)   dimension(inch)      
color1         color2

DF2


toyname   price($)     price(#)   dimension(m)   dimension(inch)  color1   color2
t1           2            12          11               21            gr       re 
t2           3            13          10               20            bl       re 
t3           12           23          20               30            ye       bl

I am looking for making individual dataframes for each toyname from DF2 using template of DF1:

t1
col1           col2
2               12
11              21
gr              re

t2
col1           col2
3               13
10              20
bl              re

2 Answers 2

1

Assuming each row represents a different toy. Try with set_index + iterrows + applymap:

dfs = {}
for i, row in df2.set_index('toyname').iterrows():
    dfs[i] = df1.applymap(lambda col: row[col])

dfs:

{'t1':   col1 col2
0    2   12
1   11   21
2   gr   re, 
't2':   col1 col2
0    3   13
1   10   20
2   bl   re, 
't3':   col1 col2
0   12   23
1   20   30
2   ye   bl}

dfs['t1']:

  col1 col2
0    2   12
1   11   21
2   gr   re

DataFrames Used:

df1 = pd.DataFrame({
    'col1': {0: 'price($)', 1: 'dimension(m)', 2: 'color1'},
    'col2': {0: 'price(#)', 1: 'dimension(inch)', 2: 'color2'}
})

df2 = pd.DataFrame({
    'toyname': {0: 't1', 1: 't2', 2: 't3'}, 'price($)': {0: 2, 1: 3, 2: 12},
    'price(#)': {0: 12, 1: 13, 2: 23}, 'dimension(m)': {0: 11, 1: 10, 2: 20},
    'dimension(inch)': {0: 21, 1: 20, 2: 30},
    'color1': {0: 'gr', 1: 'bl', 2: 'ye'},
    'color2': {0: 're', 1: 're', 2: 'bl'}
})
Sign up to request clarification or add additional context in comments.

2 Comments

how do i access individual element for dfs['t1']?
dfs['t1'] is a dataframe so the same way you would with any other dataframe. dfs['t1']['col1'] to get a column or dfs['t1'].loc[0, 'col1'] for the value at index 0 for col1 etc.
0

A simple one-liner using dict comprehension would be

dfs = {row.get('toyname'): df1.applymap(row.get) for row in df2.to_dict('records')}

print(dfs.get('t1'))

Output

  col1 col2
0    2   12
1   11   21
2   gr   re

To access data from a dataframe

data.get('t1').loc[0, 'col1']
2

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.