我有一个包含键和值列表的字典。我想制作一个简单的pandas df,但是,我无法将列表项分成不同的行。我当前的方法创建了一个df,但将值保存在列表中。如何将它们拉出来并将它们作为单独的行添加?
d = {'Car':['1','2','3'],
'Chicken legs':['4','5','6'],
'Coronary artery bypass graft surgery':['7','8','9','10','11','12']}
df = pd.DataFrame({'Thing':list(d.keys()), 'Values':list(d.values())})
Thing Values
0 Car [1, 2, 3]
1 Chicken_legs [4, 5, 6]
2 Coronary artery bypass graft surgery [7, 8, 9, 10, 11, 12]
预期的最终结果:
Thing Values
0 Car 1
1 Car 2
2 Car 3
3 Chicken_legs 4
4 Chicken_legs 5
5 Chicken_legs 6
6 Coronary artery bypass graft surgery 7
7 Coronary artery bypass graft surgery 8
8 Coronary artery bypass graft surgery 9
9 Coronary artery bypass graft surgery 10
10 Coronary artery bypass graft surgery 11
11 Coronary artery bypass graft surgery 12
答案 0 :(得分:4)
把你的字典搞得恰到好处:
In [3]: pd.DataFrame({'Thing':k, 'Values':v} for k,V in d.items() for v in V)
Out[3]:
Thing Values
0 Coronary artery bypass graft surgery 7
1 Coronary artery bypass graft surgery 8
2 Coronary artery bypass graft surgery 9
3 Coronary artery bypass graft surgery 10
4 Coronary artery bypass graft surgery 11
5 Coronary artery bypass graft surgery 12
6 Car 1
7 Car 2
8 Car 3
9 Chicken legs 4
10 Chicken legs 5
11 Chicken legs 6
答案 1 :(得分:1)
此解决方案不如juanpa.arrivillaga所接受的解决方案。
pd.concat([ pd.DataFrame({'Thing': df['Thing'][i], 'Values': pd.Series(df.Values[i])}) for i in range(len(df)) ])
Thing Values
0 Car 1
1 Car 2
2 Car 3
0 Chicken legs 4
1 Chicken legs 5
2 Chicken legs 6
0 Coronary artery bypass graft surgery 7
1 Coronary artery bypass graft surgery 8
2 Coronary artery bypass graft surgery 9
3 Coronary artery bypass graft surgery 10
4 Coronary artery bypass graft surgery 11
5 Coronary artery bypass graft surgery 12