2017-06-01 65 views
2
Date   sector weight 
0 2011-01-10  a  12 
1 2011-01-10  b  23 
2 2011-01-11  c  34 
3 2011-01-11  d  54 

回答

3

使用groupby + apply + to_json

#if necessary convert to string 
df['Date'] = df['Date'].astype(str) 
df = df.groupby('Date').apply(lambda x: dict(zip(x['sector'], x['weight']))).to_json() 
print (df) 
{"2011-01-10":{"b":23,"a":12},"2011-01-11":{"c":34,"d":54}} 
+0

谢谢@jezrael,它工作完美,我想。 – ammy

+0

很高兴能帮到你!如果我的回答很有帮助,请不要忘记[接受](http://meta.stackexchange.com/a/5235/295067)它。谢谢。 – jezrael

1
grpby = df.set_index(['Date', 'sector']).weight.groupby('Date') 
{n: g.xs(n).to_dict() for n, g in grpby} 

{'2011-01-10': {'a': 12, 'b': 23}, '2011-01-11': {'c': 34, 'd': 54}}