我想从我希望id
成为键并且所有value_x
都是值但不包括NaN
的pd.DataFrame
创建字典
数据帧newdf
:
id name value_1 value_2 value_3
0 ant jay 10.2 3.5 4.7
1 ant ann 5.7 10.2 NaN
2 bee will 7.4 NaN NaN
3 bee dave 12.4 1.3 6.9
4 bee ed 0.8 NaN NaN
5 cat kit NaN NaN 5.2
预期结果(值逐行排序(为
{ant:(10.2,3.5,4.7,5.7,10.2), bee:(7.4,12.4,1.3,6.9,0.8), cat:(5.2)}
我正在尝试使用.to_dict()
但它确实有效
newdf.groupby('id').apply(newdf.iloc[:,-3:].to_dict())
或
dict(zip(newdf.id, newdf.iloc[:,-3:]))
使用:
d = df.set_index('id').iloc[:, -3:].stack().groupby(level=0).apply(tuple).to_dict()
print (d)
{'bee': (7.4, 12.4, 1.3, 6.9, 0.8), 'cat': (5.2,), 'ant': (10.2, 3.5, 4.7, 5.7, 10.2)}
细节:
print (df.set_index('id').iloc[:, -3:].stack())
id
ant value_1 10.2
value_2 3.5
value_3 4.7
value_1 5.7
value_2 10.2
bee value_1 7.4
value_1 12.4
value_2 1.3
value_3 6.9
value_1 0.8
cat value_3 5.2
dtype: float64
如果需要订购并且可以使用pandas 0.21.0
生成OrderedDict
:
from collections import OrderedDict
d = (df.set_index('id')
.iloc[:, -3:]
.stack()
.groupby(level=0)
.apply(tuple)
.to_dict(into=OrderedDict))
print (d)
OrderedDict([('ant', (10.2, 3.5, 4.7, 5.7, 10.2)),
('bee', (7.4, 12.4, 1.3, 6.9, 0.8)),
('cat', (5.2,))])