使用带条件的 for 循环创建多个数据框

时间:2021-06-22 16:50:14

标签: python python-3.x pandas dataframe

我有两个数据框。

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

我正在寻找使用 DF1 模板为 DF2 中的每个玩具名称制作单独的数据框:

t1
col1           col2
2               12
11              21
gr              re

t2
col1           col2
3               13
10              20
bl              re

2 个答案:

答案 0 :(得分:1)

假设每一行代表一个不同的玩具。试试 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

使用的数据帧:

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'}
})

答案 1 :(得分:0)

使用 dict 理解的简单单行代码是

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

print(dfs.get('t1'))

输出

  col1 col2
0    2   12
1   11   21
2   gr   re

从数据框中访问数据

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